I can not figure out why the transform of the object the player script is attached to is returning null.
this is the Controller Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Controller : MonoBehaviour
{
Player player = new Player();
void Start()
{
player.SetEndpos(new Vector3(0f, 0f, 0f));
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
int roll = Random.Range(1, 7);
player.SetEndpos(new Vector3(roll, 0f, 0f));
}
player.Run();
}
}
This is the Player code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public Vector3 endPos = new Vector3(0f, 0f, 0f);
public void Run()
{
if (transform.position != null)
{
transform.position = endPos;
if (endPos != new Vector3(0f, 0f, 0f))
{
Debug.Log($"pos was set to: {endPos}");
}
}
}
public Vector3 GetEndpos()
{
return endPos;
}
public void SetEndpos(Vector3 end)
{
endPos = end;
Debug.Log($"endPos = {endPos}");
}
}
The null error is given at "transform.position = endPos;" in Player and "player.Run();" in Controller
The exact error message: NullReferenceException Player.Run () (at Assets/Scripts/Player.cs:11) Controller.Update () (at Assets/Scripts/Controller.cs:20)
Image: Manager Object has Controller script
Image: Player Object has the Player script
I'm sure its some stupid error I have made but I cant find a solution to this anywhere else online.
CodePudding user response:
What you need to do is to replace the Player player = new Player();
line with
public Player player;
or
[Serializable]
private Player player;
inside your controller script.
After that you will see a change in the inspector window of your controller. There should be an empty field which states "None (Player)".
Take your Player
GameObject inside your hierachy and drag it into the empty field inside the empty field.