- Home /
Why the value of caseswitch can't change ?
when I touch the gameobject, the switch value cannot change. caseswitch = 0
// Update is called once per frame
void Update()
{
gameObject.transform.position += new Vector3(0, -0.02f, 0);
ammo2time += Time.deltaTime;
switch (caseswitch)
{
case 0:
break;
case 1:
if (ammo2time > 0.30f)
{
Vector3 Bullet_pos = Ship.transform.position + new Vector3(2, 0.1f, 0);
Instantiate(ammo2, Bullet_pos, Ship.transform.rotation);
ammo2time = 0;
}
break;
default:
break;
}
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "plane")
{
Destroy(gameObject);
caseswitch = 1;
}
}
Can you please also include the full line where you declare caseswitch
first? (You may also want to give it a more descriptive name. What does it represent and what do you intend to do with it?)
the default value of caseswitch is 0 when my plane touch the power logo, the value will change to 1
In that case, you would make it a bool (true/ false), and name it e.g. touchedPowerLogo
. This way, you will be able to more easily maintain your program. You then do a check for if (touchedPowerLogo)
ins$$anonymous$$d of the case-check. In either case, to continue debugging your issue, we would need the full line where you declare that variable.
so the ammo will spawn in front of the plane
Answer by INvalidSauce · Feb 04, 2020 at 03:57 PM
You're destroying the gameobject before you try and change your variable caseswitch. When you destroy the gameobject that holds the script, it can no longer run. You need to do the destroy function AFTER "casesswitch = 1"
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "plane")
{
caseswitch = 1;
Destroy(gameObject);
}
}
EDIT: Reading a bit more into it, I don't quite get why you're destroying your gameobject. If you destroy it, you'll never get to use the variable you just changed. The switch statement in your update() won't ever do anything.
Your statement is pretty irrelevant. It doesn't really matter if you call Destroy before or after you change the variable. Destroy is delayed until the end of the current frame anyways.
Your edit is the actual answer. It's just pointless to change anything on that gameobject or its attached components if you destroy it.
and if the plane touches the box, the ammo will not follow the movement of the plane.
If I delete destroy(gameobject), it will run properly. But I want to delete the object when my plane touch it. It is because when the plane touches the box, it will give the plane buff and shoot more ammo.
Your answer
Follow this Question
Related Questions
What Is/Are... (Common Game Terms) 1 Answer
Problem with unity answers? 1 Answer
UDN Crashes On New Account 0 Answers
Latest SDK not working 0 Answers
[META] Answer is sending notification only globally? 0 Answers