我需要在 Canvas 内实例化一个预制件,已经尝试了几种解决方案,但没有一个有效。你能帮忙吗?
这是我的脚本:
class Smoke1 : MonoBehaviour
{
public GameObject myPrefab;
public GameObject canvasObject;
void Start()
{
Instantiate(myPrefab, new Vector3(0, -25, 90), Quaternion.Euler(-90, 0, 0));
myPrefab.transform.SetParent(canvasObject.transform, false);
myPrefab.transform.localScale = new Vector3(1, 1, 1);
}
}
}
我也尝试过这个:
myPrefab.transform.parent = canvasObject.transform;
最佳答案
请尝试使用此代码。
我尝试过你的代码,但它向我抛出了此错误消息:
Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption.
using UnityEngine;
public class Smoke1 : MonoBehaviour
{
public GameObject myPrefab;
public GameObject canvasObject;
void Start()
{
GameObject newSmoke = Instantiate(myPrefab, new Vector3(0, -25, 90), Quaternion.Euler(-90, 0, 0)) as GameObject;
newSmoke.transform.SetParent(canvasObject.transform, false);
newSmoke.transform.localScale = new Vector3(1, 1, 1);
}
}
您的主要问题是您试图设置 myPrefab 的 setParent,这不是您创建的实例。
关于c# - 在 Canvas 内实例化预制件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40631588/