我正在用Unity和C#创建一个2D平台游戏。我在寻找如何做到以下几点。
我有5套动画和一个gameObject(后来在游戏中应该有多个可以更改的对象,所以我们可以记住这一点),标签“Campfire0”存储在anim0
内{ {1}}。我想要的是当用户在键盘上按下E时,它将检查当前gameObject的当前动画,并将该动画更改为“Camfire25”或其他数字,如50,75或100,并更新gameObject标签。完成之后,它应该再次检查所有if语句,第二次按E时应该查看带有start function
的if语句,依此类推。
问题
我目前使用的代码如下。但问题是如下。我在start函数内部声明了每个游戏对象标签的动画制作者,但如果游戏开始,这将被触发一次。在E上第二次按下后,将出现错误“NULL”if(anim25)
。所以我认为我应该将值存储在数组中?我应该怎么做。
为了检查哪个动画是当前的动画,我使用if语句,但也可以使用foreach循环完成,还是有更短的方法来执行此操作?
当前代码:
NullReferenceException
void Update(){
public Animator anim0;
public Animator anim25;
public Animator anim50;
public Animator anim75;
public Animator anim100;
// Use this for initialization
void Start () {
count = 0;
setCountText ();
currentValue = startingValue;
//anim = GameObject.Find("Campfires").GetComponent<Animator>(); // Parent of all Campfires
anim0 = GameObject.FindGameObjectWithTag("Campfire0").GetComponent<Animator>();
anim25 = GameObject.FindGameObjectWithTag("Campfire25").GetComponent<Animator>();
anim50 = GameObject.FindGameObjectWithTag("Campfire50").GetComponent<Animator>();
anim75 = GameObject.FindGameObjectWithTag("Campfire75").GetComponent<Animator>();
anim100 = GameObject.FindGameObjectWithTag("Campfire100").GetComponent<Animator>();
}
上面的脚本第一次工作,它会将campfire标签更改为“Campfire25”并显示另一个动画片段,在第二次按E后它会给我一个 if (inTrigger){
if (Input.GetKeyDown(KeyCode.E) && count > 0){
// Update counter on press
updateCount();
if (anim0){
anim0.SetTrigger ("Campfire25");
GameObject.FindGameObjectWithTag("Campfire0").transform.tag = "Campfire25";
}
if (anim25){
Debug.Log ("hello");
anim25.SetTrigger ("Campfire50");
GameObject.FindGameObjectWithTag("Campfire25").transform.tag = "Campfire50";
}
if (anim50){
anim50.SetTrigger ("Campfire75");
transform.tag = "Campfire75";
}
if (anim75){
anim75.SetTrigger ("Campfire100");
transform.tag = "Campfire100";
}
}
}
}
的错误。这是因为启动函数将被触发。