Referencing an object in C#

Okay, so what’s wrong here? I am making a simple dodge game, and what I want my script to do is tell the enemy’s transform to go back between a set random position along the x and z axis, relative to the players position, after it passes by the player… The PlayerMove script has been attached to the player. My problem is that is looks as if I am not getting a link between the player and enemy scripts. These scripts work if I set all of the public float variables to Static, but then they won’t show up in the inspector. So, I tried to make a reference to my other scripts and this is what I have come up with:

Enemy Script:

using UnityEngine;
using System.Collections;

public class Enemy : MonoBehaviour {
	
	private float x,y,z;
	public float zAxis;
	public float moveSpeed;
	public float minSpeed = -5;
	public float maxSpeed = -7;
	public PlayerMove playerMove;
	

	// Use this for initialization
	void Start () 
	{

		RandomPosition ();
	}
	
	// Update is called once per frame
	void Update () 
	{
		//Random speed between minSpeed and maxSpeed.
		moveSpeed = Random.Range (maxSpeed,minSpeed);
		zAxis = transform.position.z;
		if (zAxis <= -10)
		{
			RandomPosition();
			minSpeed = minSpeed - .07f;
			maxSpeed = maxSpeed -.07f;
		}
				transform.Translate(Vector3.forward * moveSpeed* Time.deltaTime);
	}
		//Assign a random position along the X axis, but within the players perspective.
		void RandomPosition()
	{
		float xAxis = GameObject.Find("Player").GetComponent<PlayerMove>().xAxis;
		x = Random.Range(xAxis -15f, xAxis + 15f);
		y = 2.5f;
		z = Random.Range (10f, 15f);
		transform.position = new Vector3(x,y,z);
	}
}

PlayerMove Script:

using UnityEngine;
using System.Collections;

public class PlayerMove : MonoBehaviour {
	public float playerSpeed = 10;
	public float forwardSpeed;
	public float xAxis;
	public float distance;
	public Enemy enemy;


	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		forwardSpeed = GameObject.Find("Enemy").GetComponent<Enemy>().moveSpeed;
		xAxis = transform.position.x;
		MovePlayer ();
	}
	
	void MovePlayer(){
		
		// Ammount to Move the player
		float amtToMove = Input.GetAxis("Horizontal") * playerSpeed;
		
		
		//Method for moving the player
		transform.Translate(Vector3.right * amtToMove * Time.deltaTime);	
		
		
		
			
	}
	
			//Calculate the distance, and display it on the screen.
		void OnGUI(){
		distance = (forwardSpeed * Time.timeSinceLevelLoad / 3) * -1;
		GUI.Label (new Rect(10,10,300,20), "Distance: " + distance.ToString() + " Kilometers");
		}
	
}

In JavaScript, I would be able to just make a variable public playerMove : PlayerMove, and call it by using playerMove.xAxis, but with C# it gives me a NullReferenceException.

The error messages I keep getting read as follows:

NullReferenceException: Object reference not set to an instance of an object
Enemy.RandomPosition() (at Assets/Scripts/Enemy Scripts/Enemy.cs:38)

NullReferenceException: Object reference not set to an instance of an object
PlayerMove.Update() (at Assets/Scripts/Player Scripts/PlayerMove.cs:19)

I know it’s not the best code in the world, but it’s pretty much all I know how to do… I think I’ve done good for what I know, at least… Please, please help. I don’t know what’s wrong here…

Thank you in advance!

Well. From the code I think it can’t find a gameobject. Are you sure those are the correct names for your gameobjects?

did you set the game objects in the inspector window if they need to be set?

If your gameObjectname are correctly spell in code it should pick up them so make sure your spelling is correct.

on a side note doing GameObject.Find in update iswell known to not be good , instead you can just keep a ref of your script and catch them in start()

simply create a PlayerMove playerMove et Enemy enemy variable in each script and in start simply get the component and in your update then just do somthing like

enemy.moveSpeed or playerMove.xAxis;

you have already as I see created this 2 variable in your script just use them, or drag drop the component in it from inspector if you keep them public ( because actually they have no real purpose )

Awesome guys, thanks!

One last problem…

I’m trying to get my GameMaster Script to display the players distance through the OnGUI function. The problem is that it isn’t recording the players distance for some reason… It is staying at 0 throughout the game. The reason I want it in my GameMaster script is because whenever I lose, the player object is destroyed, and the lose screen doesn’t record the player’s distance. This is what I have for my scripts:

Update function inside PlayerMove:

	void Update () {
		xAxis = transform.position.x;
		MovePlayer ();
		float ForwardSpeed = playerSpeed;
	    distance = (ForwardSpeed * Time.timeSinceLevelLoad / 3);
	}

GameMaster Script:

using UnityEngine;
using System.Collections;

public class GameMaster : MonoBehaviour {
	//GameObject Placeholders
	public GameObject EnemyPrefab;
	public GameObject EnemyPrefab1;
	public GameObject EnemyPrefab2;
	public GameObject SlowTimePrefab;
	public GameObject PlayerPrefab;
	
	//Bools off/on
	public bool UseEnemy = true;
	public bool UseEnemy1 = true;
	public bool UseEnemy2 = true;
	
	//Misc Vars
	public float PlayerDistance;
	
	//Object Reference
	
	void Awake(){
			
		PlayerDistance = GameObject.Find("Player").GetComponent<PlayerMove>().distance;

	}
	
	// Use this for initialization
	void Start () {
		
		//Instantiate Enemies
		if(UseEnemy){
		Instantiate(EnemyPrefab);
		Instantiate(EnemyPrefab);
		Instantiate(EnemyPrefab);
		}
		if(UseEnemy1){
		Instantiate(EnemyPrefab1);
		Instantiate(EnemyPrefab1);
		}
		if(UseEnemy2){
		Instantiate (EnemyPrefab2);
		Instantiate (EnemyPrefab2);
		}
		
		//Instantiate Player
		Instantiate (PlayerPrefab);
	
	}
	
	// Update is called once per frame
	void Update () {
			
	}
	
		
		//Calculate the distance, and display it on the screen.
		void OnGUI(){
		GUI.Label (new Rect(10,10,300,20), "Distance: " + PlayerDistance.ToString() + " Kilometers");
		}
}

OnGUI Function inside Lose Script:

void OnGUI()
	{
		GUI.Label (new Rect(Screen.width / 2 - 150, Screen.height / 2 - 50, 300, 100), "Distance: " + playerMove.distance + " Kilometers");
		GUI.Label (new Rect(Screen.width / 2 - 150, Screen.height / 2 - 100, 300, 100), "Press any key to continue.");
		if (Input.anyKeyDown) //+ " \n Press any key to play again");
		{
			
			//Reset enemy speed before restart.
			enemy.minSpeed = -5;
			enemy.maxSpeed = -7;
			enemy1.minSpeed = -5;
			enemy1.maxSpeed = -7;
			enemy2.minSpeed = -7;
			enemy2.maxSpeed = -10;
			slowtime.moveSpeed = -10;
			Time.timeScale = 1.0f;
			playerMove.playerSpeed = 10;
			playerMove.transform.rotation = Quaternion.identity;
			Application.LoadLevel(0);
		}
	}

Nevermind. I figured out that I can just use a static float to hold the variable since there is just one instance of it.

Sorry for the noobness, and thank you for the help!! xP