Rad.cs:
public class Rad: MonoBehaviour
{
void show()
{
print("show in Rad");
}
}
Soud.cs:
public class Soud: MonoBehaviour
{
public Rad rad;
void Start()
{
rad=new Rad();
}
void Update()
{
rad.show();
}
}
i want to call a function(show()) from Rad class in Soud class.
But i got NullReferenceException: Object reference not set to an instance of an object.
Thanks
Shankar
ok I’m guessing your new. anything that is or inherits from a mono behavior CANNOT be created with the new keyword. Anything else can such as Vectors. you need to assign RAD from the inspector… if your creating RAD on run time use a prefab and instantiate that. keep in mind that you need an instance to instantiate you can get one from the assets folder, assigning one to a var, or getting one from the scene. for your script just assign the RAD object in the inspector.
be aware you can also just look for a an existing instance of an object
As for the error, null reference means you referencing something that is null.
unlike C++ null isn’t equal to 0
e.g x = null
So: x + 2 = undefined.
the reason your getting null is by using the new keyword to initialize the monobehaviour, this gets disallowed and thus never really happens. leaving RAD null making referencing Show impossible;
using UnityEngine;
using System.Collections;
public class RAD : MonoBehaviour {
public void Show()
{
Debug.Log("Showing Rad, this script is working!");
}
}
next script:
using UnityEngine;
using System.Collections;
public class SOUD : MonoBehaviour {
public RAD rad; //you must assign this
// Use this for initialization
void Start () {
//one way to inititlize a monobehaviour
// rad = FindObjectOfType(typeof(RAD)) as RAD;
}
// Update is called once per frame
void Update () {
rad.Show();
}
}
if your not making an object out of RAD and going to use it globally and never use an instance for it you can make it static. but be very careful when using static. with static classes and methods you can’t inherit from monobehaviour or attaching to game objects. but you can definitely reference them inside scripts. I suggest reading up on statics and researching them before using them since it can cause problems with GC(Garbage collection)
You seem new, so I’ll try to be as clear as possible. Though I would suggest you do some “my first unity game” tutorials, they should get you going in no time.
Now, if you make a new Monobehaviour
script it means it’s a component. If a script is a component you can add it to an object. This is very powerful, but requires a little getting used to if you’ve never done this kind of programming. If at this point you have no clue what I’m talking about, you should really do some beginner tutorials first.
Now, if you want to talk to a component from within an other one. All you have to do is make a public variable (like you did: public Rad rad;
) And then in the editor drag the object with that component onto the other object’s public field (it’ll be visible in the inspector.)