为什么类引用在MonoBehaviour Start()上丢失

时间:2019-06-09 02:14:38

标签: c# unity3d

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

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;
        }
    }
}

结果:

enter image description here

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

1 个答案:

答案 0 :(得分:2)

问题出在那一行:

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;

新对象已经具有此信息。