Getting a null reference when trying to access one script from an other
Hello, i'm trying to access a script from an other script, but i keep ending up for a null-reference. I feel like I've read every forum post and check every code example, and it looks like i'm doing the same thing everybody else does, and still i end up with the null-reference. Here's an example code of what i'm trying to do.
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
public TestB pCont;
// Use this for initialization
void Start () {
pCont = GetComponent<TestB>();
if (pCont.numberOne != 1)
Debug.LogWarning(pCont.numberOne);
else
Debug.LogWarning("Pcont is null");
}
// Update is called once per frame
void Update () {
}
The Test code is trying to access the "int numberOne" in TestB, but no matter what i do, i always go to the else "Debug.LogWarning("Pcont is null");" using UnityEngine; using System.Collections;
public class TestB : MonoBehaviour {
public int numberOne = 1;
void Awake()
{
}
}
Help would be greatly appreciated. MoerTa
Answer by Ahndrakhul · Feb 06, 2016 at 09:40 PM
Your if statement is saying
if pCont.numberOne does not equal 1 then LogWarning pCont.numberOne
but according to your TestB class, numberOne does equal 1, which means that you will always go through to the else statement and get the "Pcont is null" warning
you would have to change
if (pCont.numberOne != 1)
to
if (pCont.numberOne == 1)
to get the pCont.numberOne warning.
is this the only null reference you are refering to?
Your answer

Follow this Question
Related Questions
Basic Unity: Can someone explain the referencing and instantiation process? 1 Answer
Enabling & Disabling Script via On Click 1 Answer
How to make a player instantly reach to a change in gravity? 2 Answers
How do I make a enter and exit car script? 0 Answers
I know this is a basic error but i can't find out how to make my float into text here if my code, 1 Answer