C# 如何访问子对象的方法';从Unity中的父对象创建脚本
我是unity的新手,我一直在研究菜单系统。但要做到这一点,我想从父对象访问子对象的方法 我的父对象C# 如何访问子对象的方法';从Unity中的父对象创建脚本,c#,unity3d,C#,Unity3d,我是unity的新手,我一直在研究菜单系统。但要做到这一点,我想从父对象访问子对象的方法 我的父对象 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; // 1 public class buttonAnimation : MonoBehaviour , IPointerEnterHandler , IPointerExit
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems; // 1
public class buttonAnimation : MonoBehaviour
, IPointerEnterHandler
, IPointerExitHandler
{
private bool mouseOver = false;
private Vector3 startPos;
private Vector3 offsetPos;
private int offset = -20;//Change this to set the offset Amount.
// private script mousePresent;
void Start(){
startPos = transform.position;
offsetPos = startPos;
offsetPos.x = offsetPos.x + offset;
//script = gameObject.tranform.GetChild(0).GetComponent<mousePresent>();
}
void Update(){
bool s = transform.GetChild(0).GetComponent<mousePresent>().mouseHere; //This line is the error causing one
Debug.Log(s);
if(s == false){
mouseOver = false;
}
//if(script.getMousePresent() == false){
// mouseOver = false;
// }
}
}
我一直在尝试访问子对象中的mouseHere变量。我用get方法将其作为公共变量和私有变量进行了尝试。但在这两个事件中都会发生相同的错误
那就是当我试图团结一致地管理事情的时候
NullReferenceException:对象引用未设置为对象的实例
Update()(位于Assets/Main Menu/Script/buttonAnimation.cs:25)
您可以使用
返回游戏对象或其任何子对象中类型为的组件
使用深度优先搜索的儿童。
只有在活动游戏对象上找到组件时,才会返回该组件
例如:
void Start(){
//... your code
script = gameObject.GetComponentInChildren<mousePresent>();
}
void Start(){
//…您的代码
script=gameObject.getComponentChildren();
}
注意:还要确保您的子对象处于活动状态 按照标准命名准则,使用前导大写字符命名类。至于您的错误,请参阅dupe目标(这是由以下两种情况之一引起的:获取错误的子对象或脚本未附加到该对象)。
void Start(){
//... your code
script = gameObject.GetComponentInChildren<mousePresent>();
}