Hello,
I have class A with prefab populated from inspector. I’d like to call it from class B. I call it like below and got NullReference exception for Class’s A prefabButton being null.
How can I can the method from another class using destination class properties populated via inspector.
public class A: MonoBehaviour {
public GameObject prefabButton;
public void FunctionA()
{
GameObject newButton = Instantiate(prefabButton) as GameObject;
}
}
public class B: MonoBehaviour
{
public void FunctionB()
{
A populator = new A();
populator.FunctionA(items);
}
}
It will be null, because you didn’t assigned no game object to prefabButton. Your problem is that you are trying to create a MonoBehaviour with the new keyword instead of getting it as component. MonoBehaviour must be added to a game object and then the instance of the script is retreived through GetComponent().
- Create a new object in the hierarchy name it ObjectA and add the A component to it.
- Drag and drop your game object which you want to populate over the prefabButton inspector field.
- Create a new game object in the hierarchy and add component B to it.
- In class B’s method FunctionB() instead of creating “new A()” replace it with: GameObject.Find(“ObjectA”).GetComponent().FunctionA();