I'm learning Unity3D and I'm practising accessing game object scripts from other objects. For the most part I've got it down, but I've run into a weird issue causing a NullPointerException.
I've set up a GameObject, with the following script attached to it:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public Player[] players;
// Use this for initialization
void Start () {
players [0].currentPosition = 0;
players [1].currentPosition = 1;
players [2].currentPosition = 2;
}
// Update is called once per frame
void Update () {
foreach(Player p in players)
{
if(p.mFormationType == Player.FORMATIONTYPE.ATTACK)
p.transform.position = p.attackPositions[p.currentPosition];
else
p.transform.position = p.defensivePositions[p.currentPosition];
}
}
public void swapPositions(Player selected)
{
Debug.Log (selected.currentPosition);
if(selected == null)
Debug.Log("Balls - " + selected.gameObject);
if(selected.currentPosition != 0)
{
int previousPos = selected.currentPosition;
players[0].GetComponent<Player>().currentPosition = previousPos;
selected.currentPosition = 0;
}
}
}
And I've set the Player objects within the UI. I then later attempt to do this when I click on one of the Player objects:
void OnMouseOver()
{
if(this.currentPosition == 0)
return;
if(Input.GetMouseButtonDown(0))
{
PlayerController pc = this.controller.GetComponent<PlayerController> ();
pc.swapPositions (this);
}
}
But it results in an NPE within the swapPositions
method in the PlayerController class, when it attempts to access players[...]
I've stepped through and at the start of the PlayerController script they're all there and set up perfectly, but later on, they're null.
Can anyone explain why this is happening please?
Thanks in advance.
this.controller
? are you sure that the game object is pointing to has thePlayerController
component ? \$\endgroup\$controller
you are trying to use? Also can you confirmcontroller
inherits from MonoBehaviour? Thanks. \$\endgroup\$