【问题标题】:How to add gameObject in Canvas without any changes? [duplicate]如何在不做任何更改的情况下在 Canvas 中添加游戏对象? [复制]
【发布时间】:2017-08-28 18:40:21
【问题描述】:

我在 Unity 中有这个 C# 代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour {

//public GameObject Button;
public Transform Button;
public int rows;
public int columns;

// Use this for initialization
void Start () {
    int i = 0;
    int x = 0;
    int y = 0;

    for (i = 0; i < columns; i++) {
         x = 170 * rows;
         y = -170 * columns;
        Transform newButton = (Transform)Instantiate (Button, new Vector3(0,0,0), Quaternion.identity);
        newButton.parent = gameObject.transform;
        newButton.transform.localScale = new Vector3 (1, 1, 1);
        newButton.transform.parent = GameObject.Find ("Canvas").transform;
        }
    }
}

当它在克隆按钮并转换为画布时,newButton 的位置也在变化和缩放。我该怎么办?

【问题讨论】:

  • 查看副本,如果这不起作用,请告诉我,以便我快速重新打开它。 Unity 版本的行为有所不同,但您应该将 false 传递给 SetParent 函数。
  • 好的,我现在试试
  • 这行得通吗?只是想确定一下。如果不解释哪个部分不起作用。
  • newButton.GetComponent&lt;RectTransorm&gt;().anchoredPosition3D = new Vector2(x,y);这部分我加了它不识别,RectTransform和anchoredposition是红色的
  • 这似乎是另一个问题......你说的不认识它是红色的是什么意思?您可以编辑您的问题以添加更多信息和屏幕截图。

标签: c# unity3d canvas position scale


【解决方案1】:

如果要保留克隆按钮的原始位置和比例。使用Transform.SetParent 而不是设置Transform.parent。并将第二个参数worldPositionStays设置为false

Transform newButton = (Transform)Instantiate (Button, new Vector3(0,0,0), Quaternion.identity);
newButton.localScale = new Vector3 (1, 1, 1);
newButton.SetParent(GameObject.Find ("Canvas").transform, false);

【讨论】:

  • 对投票者感到好奇。他/她似乎对 U3D 组中的所有帖子都投了反对票。这样做有什么理由吗?
  • 什么都没有改变 Scale got 76.8
  • @ManeHambardzumyan 你删除了第二行newButton.parent = gameObject.transform;吗?
  • 是的,我删除了,我现在将编辑我的代码
  • @zwcloud 我看到了。高度怀疑他正在这样做。但他可能太武断了。他甚至没有看代码和答案。这就是为什么 StackOverflow 被指责不那么友好的原因。我认为这很荒谬。看到这个帖子:quora.com/Why-do-some-people-hate-Stack-Overflow
猜你喜欢
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多