【问题标题】:Why is transform.parent null in Awake() and Start()?为什么 Awake() 和 Start() 中的 transform.parent 为 null?
【发布时间】:2015-08-23 06:10:57
【问题描述】:

我正在尝试获取对脚本附加到的 GameObject 的引用。每个文档 transform.parent.gameObject 用于此目的,但 transform.parentAwake()Start() 中都是 null。我需要做什么才能使它正常工作?这可能是一个完全的菜鸟问题,但到目前为止,谷歌还没有给出一个可行的答案。

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{
    private void Awake()
    {
        var obj = transform.parent;
        Debug.Log(obj);
    }

    private void Start()
    {
        var obj = transform.parent;
        Debug.Log(obj);
    }
}

【问题讨论】:

  • 发布一些代码以获得更好的响应
  • 在这种情况下脚本没有父级,您需要做的就是使用“gameobject”访问它。 (我假设脚本附加到一个游戏对象,而不是附加到另一个游戏对象的子游戏对象,后者是您要查找的对象)
  • 谢谢!是的,情况就是这样。也请参阅我的答案。

标签: c# unity3d gameobject


【解决方案1】:

没关系!我是个白痴!它不应该是父母,但是:

var obj = transform or var obj = transform.gameObject

因为这个脚本是它应该引用的游戏对象的一部分,而不是任何父对象。我有一个奇怪的假设,即脚本是游戏对象的子对象。

【讨论】:

    【解决方案2】:

    Transform.parent 告诉您当前转换的父级是什么。 IE。如果 GameObjectAGameObjectB 的子级,则访问 GameObjectB 中的 transform.gameObject 的脚本将返回 GameObjectA

    实际上,您正在寻找的只是 gameObject。这会隐式返回您的脚本附加到的游戏对象。

    在您的场景中创建两个游戏对象。
    调用一个 GameObjectA 和另一个 GameObjectB
    将此脚本附加到 GameObjectB,然后将 GameObjectB 拖到层次结构中的 GameObjectA

    public class ExampleBehaviour : MonoBehaviour {
    
        void Awake () {
            Debug.Log(gameObject.name);        //Prints "GameObjectB" to the console
            Debug.Log(transform.parent.name);  //Prints "GameObjectA" to the console
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-07
      • 1970-01-01
      • 2014-10-21
      • 2017-04-09
      • 2019-07-22
      • 2017-04-02
      • 2017-09-03
      相关资源
      最近更新 更多