- Home /
Why this Texture gives value of Null when I access it from other script
So I want to access a Texture variable that is another script from other script.
public class AssignMaterial : MonoBehaviour {
public Texture required;
void Start ()
{
required = Resources.Load("Textures/Brown") as Texture;
}
}
public class DragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
AssignMaterial texture;
public void Start()
{
texture = new AssignMaterial();
}
public void OnEndDrag (PointerEventData eventData)
{
Debug.Log(texture.required.name);
}
}
The result is NullReferenceException: Object reference not set to an instance of an object
Answer by maccabbe · Apr 07, 2015 at 07:20 PM
The monobehaviour is created incorrectly, it needs to be attached to a gameObject in order for Unity to automatically call the monobehaviour methods (such as Start where the object reference is created).
One way to fix this is to properly attach the monobehaviour by replacing line 20 with
texture=gameObject.AddComponent<AssignMaterial>();
A second way to fix this is to not use a monobehaviour and instead rely on a constructor by replacing AssignMaterial's code with
public class AssignMaterial{
public Texture required;
public AssignMaterial()
{
required = Resources.Load("Textures/Brown") as Texture;
}
}
Your answer
Follow this Question
Related Questions
How to check against the object type of an instance 1 Answer
How can I modify a variable on an instance of a prefab after I created it? 2 Answers
Referencing instance of game object hit via RaycastHit 1 Answer
After update of Unity Editor all objects in scene lost references to any scene object. 2 Answers
Can't reference Camera in Prefab 1 Answer