Hey guys so I have this really strange problem, so basically what happens is the player runs into the box (OnTriggerEnter function) and a weapon will show on the character and the box will spawn to another location. Except I tried to make a separate script because the script that it works on is for spawning boxes. I didn't want it in the same script because not as neat.
So this is my code for the script where it doesn't work:
public class ChangeGun : MonoBehaviour {
public Sprite gunSprite;
private string[] weapons = { "Pistol", "Shotgun", "Ak47", "Bazooka" };
public GameObject currentGun;
public void AddGunToPlayer()
{
//int randomNumber = Random.Range(0, 4);
currentGun.GetComponent<SpriteRenderer>().sprite = gunSprite;
}
}
And this is the script where it works (keep in mind I used the EXACT same code, ignore all the code in this script except the for the 2 variables and the OnTriggerEnter Function.)
public class BoxGenerator : MonoBehaviour
{
public GameObject currentGun;
public Sprite gunSprite;
public Vector3[] boxPositions;
public GameObject box;
public GameObject startingBox;
int randomNumber;
// Use this for initialization
void Start()
{
//random number between 0-10 thats vector size
randomNumber = Random.Range(0, 10);
//instantiate the starting box
startingBox = Instantiate(box);
//set starting box to new location
startingBox.transform.position = boxPositions[randomNumber];
//set tag to box
startingBox.tag = "box";
}
void Update()
{
randomNumber = Random.Range(0, 10);
}
void OnTriggerEnter(Collider col)
{
if (col.GetComponent<Collider>().tag == "box")
{
startingBox.transform.position = boxPositions[randomNumber];
currentGun.GetComponent<SpriteRenderer>().sprite = gunSprite;
}
}
}
Keep in mind when I tried to use the old script under this line "currentGun.GetComponent().sprite = gunSprite;"
I pasted this code and got the null reference exception.
ChangeGun cg = new ChangeGun();
cg.AddGunToPlayer();