首页 > 解决方案 > 为什么 MonoBehaviour Start() 上的类引用丢失

问题描述

我在静态方法中创建了一个新 GameObject 的实例,并在其中设置了所有 GameObject 字段。但是,当我尝试从 Start() 获取字段时,引用属性为空。

public class Hero : MovableStrategicObject
{
    public string heroName;
    public Player conrtollingPlayer;

    protected new void Start()
    {
        base.Start();
        Debug.Log("2 - Hero name: " + heroName);
        Debug.Log("2 - Controlling player exists: " + (conrtollingPlayer != null));
        Debug.Log("2 - Tile exists: " + (currentTile != null)); // Inherited attribute
    }

    public static GameObject Spawn(Tile tile, Player player, string name, string prefabPath = "Heroes/HeroPrefab")
    {
        GameObject o = MovableStrategicObject.Spawn(prefabPath, tile);
        var scripts = o.GetComponents(typeof(MonoBehaviour));
        Hero hero = null;

        foreach (MonoBehaviour s in scripts)
        {
            if (s is Hero)
                hero = s as Hero;
        }

        if (hero != null)
        {
            Instantiate(o, (Vector2)tile.gameObject.transform.position, Quaternion.identity);
            o.GetComponent<Hero>().conrtollingPlayer = player;
            o.GetComponent<Hero>().heroName = name;
            Debug.Log("1 - Hero name: " + o.GetComponent<Hero>().heroName);
            Debug.Log("1 - Controlling player exists: " + (o.GetComponent<Hero>().conrtollingPlayer != null));
            Debug.Log("1 - Tile exists: " + (o.GetComponent<Hero>().currentTile != null)); // Inherited attribute

            return o;
        }
        else
        {
            Debug.Log("Object (" + prefabPath + ") has no Hero script attached.");
            return null;
        }
    }
}

结果:

在此处输入图像描述

PS 您可以确定它是正确的游戏对象,因为英雄名称和所有派生属性都已正确分配。

标签: c#unity3d

解决方案


问题出在这一行:

Instantiate(o, (Vector2)tile.gameObject.transform.position, Quaternion.identity);

因为这个对象是 GameObject 的一个新实例,所以与前一个对象的所有分配都不会影响这个实例。所以修复是:

GameObject h = Instantiate(o, (Vector2)tile.gameObject.transform.position, Quaternion.identity);
h.GetComponent<Hero>().conrtollingPlayer = player;
h.GetComponent<Hero>().heroName = name;

return h;

新对象已经具有此信息。


推荐阅读