- Home /
Not a bug. Error in programmer expectations
Unity 4.6's button Bug?
This is my simple script:
using UnityEngine;
using System.Collections;
public class bt : MonoBehaviour {
public bool mouseOver = false;
public GameObject cube;
public Transform tran;
private GameObject go;
public void Enter()
{
mouseOver = true;
go = Instantiate(cube, tran.position, tran.rotation) as GameObject;
}
public void Exit()
{
Destroy(go);
mouseOver = false;
}
void Update()
{
if(mouseOver)
{
if(Input.GetButtonUp ("Fire1"))
{
Destroy(go);
}
if(Input.GetButtonUp ("Fire2"))
{
Destroy(go);
print ("dose it work???");
}
}
}
}
I add two EvenTrigger on my Button (which the script was attached to). One call Enter() when PointerEnter and one call Exit() when PointerExit.
The problem is when Left click (Fire1) the object is destroyed. But when I press Right Click (Fire2) the object isn't destroyed (the print command still works)......Help me please, thank all.
Answer by Jeff-Kesselman · Nov 16, 2014 at 05:10 PM
There is no bug. Destroy is working exactly as documented.
rtfm http://docs.unity3d.com/ScriptReference/Object.Destroy.html
can't you tell me where is that "programmer expectations"????? You just click "Fire3" which does not contain in that script it would give the same result (that new object have instantiate)......
@$$anonymous$$hdaubu2, Once Destroy is called the gameobject "go" is destroyed and deleted from memory. So when you left click, Input.GetButtonUp ("Fire1") is called which deletes "go" from memory. Now when you right click, Input.GetButtonUp ("Fire2") is called. When you try to Destroy "go" the second time Unity cannot destroy the gameobject "go", because it is already destroyed and not in memory. So the call to Destroy the second time does nothing.
So you get this:
if(Input.GetButtonUp ("Fire1"))
{
//"go" is destroyed and deleted from memory. "go" is now null.
Destroy(go);
}
if(Input.GetButtonUp ("Fire2"))
{
//"go" does not exist anymore. So Destroy(go) equals
//Destroy(nothing)
Destroy(go);
print ("dose it work???");
}