- Home /
Question is of type NullReferenceException
Object reference not set to an instance of an object? C#
using UnityEngine;
using System.Collections;
public class GetInOutShip : MonoBehaviour {
//Variables
bool inShip = false;
public Camera camera;
public ShipController shipController;
public FirstPersonController firstPersonController;
public GameObject ship;
public GameObject player;
public Transform cameraTransform;
void Start () {
inShip = false;
player.SetActive (true);
ship.SetActive (true);
GameObject.Find ("Spacship_vehicle").GetComponent<ShipController> ().enabled = false;
GameObject.Find ("Player_player").GetComponent<FirstPersonController> ().enabled = true;
cameraTransform = Camera.main.transform;
}
void Update () {
if (Input.GetKeyDown (KeyCode.P)) {
Invoke ("IntoShip", 0);
}
}
void IntoShip() {
Debug.Log ("Entered the Ship");
GetComponent<FirstPersonController> ().enabled = false;
GetComponent<ShipController> ().enabled = true;
inShip = true;
cameraTransform.parent = transform;
}
void ExitShip () {
Debug.Log ("Left the Ship");
}
}
The error is on line 41. Someone please help i dont have a clue?
Do you have a FirstPersonController and a ShipController component on this GameObject?
Your component is on a different object since you use the same line in the start by finding first the object holding that script.
Ah, I think I see the thing, in Start() you look for particular objects then set their components enabled or not.
In IntoShip() you don't look for other objects, so it's looking for those components on the current object, but it doesn't have them (they're on those other objects) hence the error.
I think that making the lines in IntoShip() look like those in Start() would probably fix the error. But the Find (and to a lesser extent GetComponent) calls are expensive, so you'd be better off storing these components in your firstPersonController and shipController variables (probably making them private too), and then you'll just be able to do firstPersonController.enabled = true
and so on
Hello, sorry i was out, i do not have both scripts on the gameobject so how would i reference to it in this script?
Answer by meat5000 · Feb 25, 2015 at 08:17 PM
You are not actually doing anything with your gameobject.Find calls. You make the calls but you dont store the result!
Store the gameobject references and use getcomponent from them to access the scripts kept on them.
someGameObject.GetComponent<Script>().variable
Follow this Question
Related Questions
help I know I'm over looking something 0 Answers
Object not set to a reference(again) 1 Answer
Network Respawn Object not set... 0 Answers
NullReferenceException Error 1 Answer
Object reference not set to an instance of an object... again 1 Answer