我的团契很难
本文关键字:很难 我的 | 更新日期: 2023-09-27 18:28:07
嗨,我有一个附加到主摄像头的脚本,在这个脚本中,我想选择一个0到5之间的数字。根据我得到的数字,我希望运行一个脚本。她是我的剧本,附在主摄像头上。我一直收到这个错误
NullReferenceException:对象引用未设置为对象RandomFunction.Start()的实例(位于Assets/Resources/Scripts/RandomFunction.cs:22)
using UnityEngine;
using System.Collections;
public class RandomFunction : MonoBehaviour {
int n;
void Awake()
{
GetComponent<RandomFunction> ().enabled = true;
}
void Start ()
{
n=Random.Range(0,5);
if(n==0)
{
GetComponent<BlueGoUp> ().enabled = true;
}
else if(n==1)
{
GetComponent<RedGoUp> ().enabled = true;
}
else if(n==2)
{
GetComponent<GreenGoUp> ().enabled = true;
}
else if(n==3)
{
GetComponent<OrangeGoUp> ().enabled = true;
}
else if(n==4)
{
GetComponent<YellowGoUp> ().enabled = true;
}
else if(n==5)
{
GetComponent<PurpleGoUp> ().enabled = true;
}
}
}
- 删除
Awake()
方法,因为确实没有必要从这里激活RandomFunction
脚本。在检查员中激活 - 我不确定像这样使用组件是否正确。我总是使用
gameObject.GetComponent
- 因为CCD_ 5返回CCD_ 6,所以CCD_。从文档中:
Range(intmin,intmax),返回介于min[包含]和max[排除]之间的随机整数(只读)。
- 使用
switch case
语句而不是If else
您的最终代码应该是这样的:
using UnityEngine;
using System.Collections;
public class RandomFunction : MonoBehaviour {
int n;
void Start ()
{
n=Random.Range(0,6);
switch (n)
{
case 0:
gameobject.GetComponent<BlueGoUp> ().enabled = true;
break;
case 1:
gameObject.GetComponent<RedGoUp> ().enabled = true;
break;
case 2:
gameObject.GetComponent<GreenGoUp> ().enabled = true;
break;
case 3:
gameObject.GetComponent<OrangeGoUp> ().enabled = true;
break;
case 4:
gameObject.GetComponent<YellowGoUp> ().enabled = true;
break;
case 5:
gameObject.GetComponent<PurpleGoUp> ().enabled = true;
break;
default:
break;
}
}
}
因此,首先,您不需要在Awake函数中执行您正在执行的操作,因为:
- 使用的MonoBehavior对象是附加到GameObject的对象。如果你不明白我的意思,假设你把
RandomFunction
附加到CameraObj。现在,RandomFunction
的实例(脚本中的this
指针)等于或等于CameraObj.GetComponent<RandomFunction>()
,因为不能向GameObject添加多个相同组件 - 在对象实际启用之前,
Awake()
方法不会执行因此,您不需要在脚本中重新启用对象,因为如果它正在执行,则该对象已经启用
删除Awake
方法,它也应该删除NullReferenceException
。如果仍然没有,请确保同一对象(具有RandomFunction
组件)也具有组件BlueGoUp
、RedGoUp
、YellowGoUp
、GreenGoUp
、OrangeGoUp
和PurpleGoUp
。
哦,你的if (n==5)
条件永远不会成立,因为Random.Range()
永远不会返回5。max
参数始终是Random.Range()
函数中整数的互斥参数,因此返回的值始终为min <= value < max
。
很可能,我希望所有的GoUp脚本都没有附加到相机上。所以用另一种方式找到脚本。尝试用这个替换你的代码,
using UnityEngine;
using System.Collections;
public class RandomFunction : MonoBehaviour {
int n;
void Awake()
{
GetComponent<RandomFunction> ().enabled = true;
}
void Start ()
{
n=Random.Range(0,6);
switch(n){
case 0:
FindObjectOfType<BlueGoUp>().enabled = true;
break;
case 1:
FindObjectOfType<RedGoUp>().enabled = true;
break;
case 2:
FindObjectOfType<GreenGoUp>().enabled = true;
break;
case 3:
FindObjectOfType<OrangeGoUp>().enabled = true;
break;
case 4:
FindObjectOfType<YellowGoUp>().enabled = true;
break;
case 5:
FindObjectOfType<PurpleGoUp>().enabled = true;
break;
}
}
}
如果这个代码不起作用,那么除了你的脚本不被放在任何游戏对象上之外,别无选择。