- Home /
Texture2D is Null even though hooked up in Inspector.
I am trying to draw a 2D texture as part of a reticule in my game. I have a Texture2D in my script and have it hooked up to a png in the inspector. When I try to use it I just get Null reference exceptions. I can programatically make a texture which works and I can see the quad I want but I want to use the png texture. This is the basics of what I have: public class Ship : MonoBehaviour { public Texture2D crosshair;
Texture2D sameTeamTexture;
Texture2D enemyTeamTexture;
void Start()
{
/*sameTeamTexture = new Texture2D(10, 10);
for(int i =0; i < sameTeamTexture.width; ++i)
{
for(int j=0; j < sameTeamTexture.height; ++j)
{
sameTeamTexture.SetPixel(i, j, new Color( 1, 1, 1, 1 ) );
}
}
sameTeamTexture.Apply();
enemyTeamTexture = new Texture2D(10, 10);
for(int i =0; i < enemyTeamTexture.width; ++i)
{
for(int j=0; j < enemyTeamTexture.height; ++j)
{
enemyTeamTexture.SetPixel(i, j, new Color( 1, 0, 0, 1 ) );
}
}
enemyTeamTexture.Apply();*/
}
void OnGUI()
{
DrawCrosshair( Vector3.zero, 100.0f, true, false );
var players = PlayerTracker.GetAllPlayerInfos();
var myPlayerInfo = PlayerTracker.MyPlayerInfo;
foreach( PlayerInfo player in players )
{
if ( player != myPlayerInfo )
{
Vector3 screenPos = Camera.mainCamera.WorldToScreenPoint( player.transform.position );
float border = 100.0f;
DrawCrosshair( screenPos, border, false, player.PlayerTeam == myPlayerInfo.PlayerTeam );
}
}
}
private void DrawCrosshair( Vector3 screenPos, float border, bool drawWhenVisible, bool sameTeam )
{
// snap position and display texture
screenPos.x = Mathf.Clamp( screenPos.x, border, Camera.mainCamera.GetScreenWidth() - border );
screenPos.y = Mathf.Clamp( screenPos.y, border, Camera.mainCamera.GetScreenHeight() - border );
/* debug - draw quad
Texture2D tex;
if ( sameTeam )
{
GUI.color = new Color( 1, 1, 1, 1 );
tex = sameTeamTexture;
}
else
{
GUI.color = new Color( 1, 0, 0, 1 );
tex = enemyTeamTexture;
}
GUI.DrawTexture(new Rect( screenPos.x,
Camera.mainCamera.GetScreenHeight() - screenPos.y,
tex.width,
tex.height),
tex, ScaleMode.StretchToFill, false);*/
GUI.DrawTexture(new Rect( screenPos.x - (crosshair.width * 0.5f),
screenPos.y - (crosshair.height * 0.5f),
crosshair.width,
crosshair.height),
crosshair, ScaleMode.ScaleToFit, false);
}
What am I failing to do to get this working? Thanks Allan
Usually when this happens, you will find that you have the script attached to two different object, one with the value assigned in the inspector, and one still unassigned.
Thanks, I got it working. I was adding the textures to the instance of the prefabs ins$$anonymous$$d of the base prefab. Now it is working :-)
Your answer
Follow this Question
Related Questions
Handling NullReferenceException in EditorWindow OnGUI() 0 Answers
Mathf.Lerp 2 Answers
Create Texture2D elements in OnGUI Method 1 Answer