1.在one1脚本中获取one2代码的数值时,为什么在Start()中写game1 = GetComponent();会报错(NullReferenceException: Object reference not set to an instance of an object
One1.Update () (at Assets/Scripts/One1.cs:22)
),而在update()中直接用game1.GetComponent().Mesh(a1);调用方法没有问题。(只要一写game1 = GetComponent();无论后面updata()中是否写game1.GetComponent().Mesh(a1);都会报同样的错。)
2.为什么在One2脚本中打印的是:2:0,1:1。而不是2:1,1:1。按道理说a2的值应该传入出去的但为什么没有传入?该怎么改让a2的值为1。即打印的是2:1。
其中已经确认是a1正确传入过来,外部接口拖入正确,带相关脚本的游戏物体正确配置,且启用。
相关代码:
One1中:
public class One1 : MonoBehaviour
{
public One2 game1;//带有脚本One2的游戏物体
private float a1=1;
private void Awake()
{
game1 = GetComponent();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
game1.GetComponent().Mesh(a1);
}
}
One2中:
public class One2 : MonoBehaviour
{
private float a2=0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Debug.Log("2:"+a2);
}
public void Mesh(float a)
{
a2 = a;
Debug.Log("1:"+a);
}
}
你还是没有搞清楚什么叫对象
同一个脚本,可以挂在很多个GameObject上面,那么它就有很多个实例
game1 获取到的是一个实例,one2挂载的物体下面是另一个实例,当然传不了
game1 = GetComponent();的意思是game1 = this.GetComponent();,这是把当前物体下的one2脚本赋值给game1
而game1.GetComponent()是获取game1下面的one2脚本
public One2 game1;//带有脚本One2的游戏物体,这里注释不正确,这就是one2脚本,而不是物体,物体类型是GameObject
根源就在于你引入的只是脚本,而不是物体
换句话说你的game1是个单独的实例,而不是one2脚本挂载的物体实例
那么既然game1根本没有挂在物体下面,update方法当然不会走,所以也不会打印。打印的是挂在物体下面的那个脚本
-==-=-==
修改方法:
你需要2个变量,一个是类型是gameobject,比如起名叫obj,要拖入挂载one2脚本的物体;还有一个是one2,用来获取脚本
其中one2不需要是public的,不需要从外部拖入,start的时候获取即可,但是不能用this.GetComponent,而应该写obj.GetComponent
这里也可以通过物体名字find到物体的实例,而无需拖入,也可以直接反射执行脚本函数,而无需one2对象,这个方法稍微复杂,但是对于需要循环操作不同类型的物体和脚本更有效,否则要定义一大堆类型并写一大堆if,else