I’m trying to use RayCastHit to loot enemies.The problem is, I can’t figure out how to stop the raycast from hitting objects after the enemy has already been selected. For example, you look at the enemy, press “E” to open it’s inventory (which works fine), but when you move your mouse while the inventory is open you get a NullReferenceException because the raycast is hitting a wall instead of an enemy.
Here’s my code:
function OnGUI()
{
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
var enemy : GameObject;
if (Physics.Raycast (ray, hit, 100))
{
if(hit.collider.tag == "Enemy" && !hit.collider.gameObject.GetComponent(enemyScript).alive)
{
GUI.Label(Rect(Screen.width / 2, Screen.height / 2,40,40),"[E] Loot");
if(Input.GetKey(KeyCode.E))
{
lootable = true;
}
}
}
if(lootable)
{
GUI.BeginGroup(Rect(Screen.width / 2 -100 , Screen.height / 2 -200, 200,200));
GUI.Box(Rect(0,0,200,200), "");
GUI.Label(Rect(10, 5, 150, 40), "Enemy");
GUI.Button(Rect(10, 15, 150, 40), enemy.gameObject.GetComponent(enemyScript).lootItem1.name);
GUI.Button(Rect(10, 25, 150, 40), enemy.gameObject.GetComponent(enemyScript).lootItem2.name);
GUI.EndGroup();
if(Input.GetKey(KeyCode.Escape))
{
lootable = false;
}
}
}
Can anyone fix this?
Not sure, but I think you can just insert at between lines 16 and 17: else { lootable = false; }
– robertbu