- Home /
Answer found by the OP
GetComponent returns null reference
Hello, I am trying to fill a wineglass. In order to fill it it must be empty, but Unity keeps throwing an exception saying null reference. I know what null reference is, but I have no idea why it is doing it here.
If I put in:
print(target)
It correctly returns the name of the object that the raycast hits.
This is the line that is throwing an error:
if(target.GetComponent<WineGlass>().empty == true)
And this is the entire code:
RaycastHit hit;
if (Physics.Raycast(cameraTransform.position, cameraTransform.TransformDirection(Vector3.forward), out hit, 2.0f)) {
GameObject target;
target = hit.collider.gameObject;
switch (hit.collider.tag) {
case "WineGlass":
print("WAT");
if(GameManager.CurrentItem == GameManager.item.WineBottle){
if(target.GetComponent<WineGlass>().empty == true){
interfaceManager.WriteMessage("You fill the glass");
GameManager.FilledWineglassCount += 1;
target.SendMessage("FillGlass");
if (GameManager.FilledWineglassCount == 10){
CompletePuzzle();
GameManager.PuzzleWineComplete = true;
}
}
}
break;
And the following is the script attached to the object:
public class WineGlass : MonoBehaviour {
public bool empty;
// Use this for initialization
void Start () {
empty = true;
}
// Update is called once per frame
void Update () {
}
public void FillGlass () {
empty = false;
print("Filling glass...");
}
public void EmptyGlass () {
empty = true;
print("Emptying glass...");
}
}
I am sure it is just something that I don't understand, please help
Best Regards EKN
Sorry, rookie mistake, forgot to add the WineGlass script to the wineglass objects!
Leaving the question here because it may be usefull for others
Follow this Question
Related Questions
GetComponent doesn't work anymore 2 Answers
NullReference when calling a function to another script 2 Answers
access enum values 0 Answers
GetComponent not working C# 1 Answer
A simple CS0309 problem... 2 Answers