I have created a script that randomly applies a buff to both players in my game, it first accesses the players scripts and sets a certain bool to on or off to avoid the effects stacking within the script, however i keep getting this error for the bools from the other scripts.
NullReferenceException: Object reference not set to an instance of an object
Slots+<Spin>c__Iterator0.MoveNext () (at Assets/Slots.cs:85)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
UnityEngine.MonoBehaviour:StartCoroutine(String)
Slots:Start() (at Assets/Slots.cs:19)
Btw, the line for where the error occurs depends on the number generated.
here is the code which is having problems.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Slots : MonoBehaviour {
public Animator anim;
public Player Player1;
public Player Player2;
public bool Giga;
public bool Speed;
public bool Fire;
public bool Dark;
public int random;
// Use this for initialization
void Start () {
StartCoroutine ("Spin");
}
// Update is called once per frame
void Update () {
Player1 = GameObject.FindWithTag ("Player").GetComponent<Player> ();
Player2 = GameObject.FindWithTag ("Player2").GetComponent<Player> ();
anim.SetBool ("Giga", Giga);
anim.SetBool ("Speed", Speed);
anim.SetBool ("Fire", Fire);
anim.SetBool ("Dark", Dark);
}
IEnumerator Spin(){
random = Random.Range (1, 5);
if (random == 1) {
Giga = true;
Player1.Big = true;
Player1.transform.localScale = new Vector3 (2, 2, 2);
Player2.Big = true;
Player2.transform.localScale = new Vector3 (2, 2, 2);
yield return new WaitForSeconds (20f);
Player1.Big = false;
Player1.transform.localScale = new Vector3 (1, 1, 1);
Player2.Big = false;
Player2.transform.localScale = new Vector3 (1, 1, 1);
}
if (random == 2) {
Speed = true;
Player1.Fast = true;
Player1.maxSpeed = Player1.maxSpeed * 2f;
Player2.Fast = true;
Player2.maxSpeed = Player2.maxSpeed * 2f;
yield return new WaitForSeconds (20f);
Player1.Fast = false;
Player1.maxSpeed = Player1.maxSpeed / 2f;
Player2.Fast = false;
Player2.maxSpeed = Player2.maxSpeed / 2f;
}
if (random == 3) {
Fire = true;
Player1.Fire = true;
Player2.Fire = true;
yield return new WaitForSeconds (20f);
Player1.Fire = false;
Player2.Fire = false;
}
if (random == 4) {
Dark = true;
Player1.Grav = true;
Player1.rb2d.gravityScale = Player1.rb2d.gravityScale / 3f;
Player1.rb2d.mass = Player1.rb2d.mass / 1.2f;
Player2.Grav = true;
Player2.rb2d.gravityScale = Player2.rb2d.gravityScale / 3f;
Player2.rb2d.mass = Player2.rb2d.mass / 1.2f;
yield return new WaitForSeconds (20f);
Player1.Grav = false;
Player1.rb2d.gravityScale = Player1.rb2d.gravityScale * 3f;
Player1.rb2d.mass = Player1.rb2d.mass * 1.2f;
Player2.Grav = false;
Player2.rb2d.gravityScale = Player2.rb2d.gravityScale * 3f;
Player2.rb2d.mass = Player2.rb2d.mass * 1.2f;
}
}
}