• 0

[C#] Door animation script in Unity. IF statement issue.


Question

Hi guys,

 

Hoping someone here can help me with C# and Unity.

 

I'm working on a project and trying to animate a door I created in 3DS max. I've attached a script to a switch in the scene and press it. It isn't acting as I would expect.

 

Instead of playing the open animation, it just plays the close animation every time I interact with the switch.
Adding the Debug lines, shows that "First" is passed twice for every interaction and "Closed" and "Opened" are passed once each. I'm struggling to see why this is and hoping a fresh pair of eyes could spot the issue and suggest a solution.

using UnityEngine;
using System.Collections;

public class DoorSwitch : MonoBehaviour 
{
	public GameObject door;
	public GameObject button;
	public bool isDoorOpen = false;

	private GameObject player;

	// Use this for initialization
	void Awake () 
	{
		player = GameObject.FindGameObjectWithTag(Tags.player);
	}

	void OnTriggerStay (Collider other) 
	{
		if(other.gameObject == player)
			if(Input.GetButtonDown("Switch"))
				DoorToggle();
	}

	void DoorToggle()
	{
		Debug.Log("First");
		if(isDoorOpen == true)
		{
			isDoorOpen = false;
			door.animation.Play("Closing");
			button.renderer.material.color = Color.red;
			Debug.Log("Closed");
		}
		else if(isDoorOpen == false)
		{
			isDoorOpen = true;
			door.animation.Play("Opening");
			button.renderer.material.color = Color.green;
			Debug.Log("Opened");
		}
	}
}

16 answers to this question

Recommended Posts

  • 0

If you just want to use a last used timer you only need a few lines:

 

        static readonly TimeSpan DoorDelay = TimeSpan.FromSeconds(3);
        DateTime lastDoorToggle = DateTime.MinValue;

        public void DoorToggle()
        {
            DateTime now = DateTime.Now;
            if (now.Subtract(lastDoorToggle) < DoorDelay)
                return;

            lastDoorToggle = now;

            Debug.Log("Door animation runs");
            // rest of door logic
        }
This way you have no timers running that you don't need.
  • 0

Looks fine to me.  The only thing I can think of is that the switch is being triggered twice.  You could add in a timeout that if the switch is hit within 3 seconds (or something) of the last hit you ignore it.

  • 0
  On 13/04/2015 at 18:22, Seabizkit said:

yeah looks fine but my guess is that your creating a new DoorSwitch each time... i would need to understand how this is consumed to ensure that there is only one instance and the same instance of the DoorSwitch

Yea, was thinking that after too.  That maybe you are binding two cases in case of on/off but without seeing how you bind, it's hard to say for sure.

  • 0

I've added these three screenshots.

 

The first shows the switch and the inspector, I've looked at all items in the hierarchy to make sure I haven't added the script to another object.

The second is the imported animations, not sure if there's any settings there that I should tweak. The same goes for the third screenshot of the door model in the hierarchy.
 

post-438852-0-67093800-1428949795.png

post-438852-0-43131100-1428949853.png

post-438852-0-48379000-1428949880.png

  • 0
  On 13/04/2015 at 18:19, firey said:

Looks fine to me.  The only thing I can think of is that the switch is being triggered twice.  You could add in a timeout that if the switch is hit within 3 seconds (or something) of the last hit you ignore it.

 

Still finding my way around C# and Unity, any pointers to how I could make a timeout for the switch? I've tried reading up about Coroutines and IEnumerator, but I'm not sure how to implement it within the script.

  • 0
  On 13/04/2015 at 19:06, DaveGreen93 said:

Still finding my way around C# and Unity, any pointers to how I could make a timeout for the switch? I've tried reading up about Coroutines and IEnumerator, but I'm not sure how to implement it within the script.

I'm not entirely sure how unity works.  You could do it a couple ways, the simplest approach is to do something like this:

 

bool ignoreSwitch = false;
timer tmrIgnore;

protected void initialize() 
{
   tmrIgnore = new timer();
   tmrIgnore.Interval = 3000;
   tmrIgnore.Tick += new tmrIgnore_tick();
   tmrIgnore.Enabled = false;
}

protected void tmrIgnore_tick() 
{
    ignoreSwitch = false;
    tmrIgnore.Enabled = false;
}

protected void toggleDoor()
{
   if (!ignoreSwitch) {
      //run your code
      ignoreSwitch = true;
      tmrIgnore.Enabled = true;
   }
}

It's a really rough concept and by no means the best.  I mean ideally unity would give you ticks that you could just keep track of (ticks since last call).  However it should give you an idea.

  • 0
  On 13/04/2015 at 19:29, firey said:

I'm not entirely sure how unity works.  You could do it a couple ways, the simplest approach is to do something like this:

 

bool ignoreSwitch = false;
timer tmrIgnore;

protected void initialize() 
{
   tmrIgnore = new timer();
   tmrIgnore.Interval = 3000;
   tmrIgnore.Tick += new tmrIgnore_tick();
   tmrIgnore.Enabled = false;
}

protected void tmrIgnore_tick() 
{
    ignoreSwitch = false;
    tmrIgnore.Enabled = false;
}

protected void toggleDoor()
{
   if (!ignoreSwitch) {
      //run your code
      ignoreSwitch = true;
      tmrIgnore.Enabled = true;
   }
}

It's a really rough concept and by no means the best.  I mean ideally unity would give you ticks that you could just keep track of (ticks since last call).  However it should give you an idea.

 

Hmmm, timer isn't included in Unity. Guess I'll have to research Coroutines more. Hopefully my lecturer can get back to me asap.

 

Thank you for your time and ideas firey.

  • 0
  On 13/04/2015 at 19:54, DaveGreen93 said:

Hmmm, timer isn't included in Unity. Guess I'll have to research Coroutines more. Hopefully my lecturer can get back to me asap.

 

Thank you for your time and ideas firey.

No problem, sorry I couldn't offer more assistance.  

  • 0
  On 13/04/2015 at 19:06, DaveGreen93 said:

Still finding my way around C# and Unity, any pointers to how I could make a timeout for the switch? I've tried reading up about Coroutines and IEnumerator, but I'm not sure how to implement it within the script.

 

I think a hint to the solution is in the documentation of your event:

 

  Quote

 

OnTriggerStay is called once per frame for every Collider other that is touching the trigger

 

keyword: Once per frame. You could try to add yield after the Call to your DoorToggle(), but I have not read up on how they work With events.  Or add a timestamp that cancels the Logic if the event is triggered within x milliseconds. 

  • 0
  On 14/04/2015 at 14:58, Eric said:

If you just want to use a last used timer you only need a few lines:

 

        static readonly TimeSpan DoorDelay = TimeSpan.FromSeconds(3);
        DateTime lastDoorToggle = DateTime.MinValue;

        public void DoorToggle()
        {
            DateTime now = DateTime.Now;
            if (now.Subtract(lastDoorToggle) < DoorDelay)
                return;

            lastDoorToggle = now;

            Debug.Log("Door animation runs");
            // rest of door logic
        }
This way you have no timers running that you don't need.

 

 

Excellent, thank you Eric! After adding using System; it worked flawlessly. My lecturer was useless in helping.

 

Also, thank you everyone else for your suggestions.

  • 0

Hi DaveGreen93

 

Not that I care about unity but i do care about my understanding of c# logic.

 

Could you explain why this works and your original does not, as to me its in either one of two states..."open" or "closed".

 

If there is an instance of DoorSwitch per a door then i don't understand why the original logic doesn't work.

 

Could you explain how a timer fixes the issue.

 

Thanks

  • 0
  On 14/04/2015 at 17:09, Seabizkit said:

Hi DaveGreen93

 

Not that I care about unity but i do care about my understanding of c# logic.

 

Could you explain why this works and your original does not, as to me its in either one of two states..."open" or "closed".

 

If there is an instance of DoorSwitch

per a door then i don't understand why the original logic doesn't work.

 

Could you explain how a timer fixes the issue.

 

Thanks

Behavior scripts in Unity are trigged for as long as the input is active so even a quick click on a switch could result in the event firing multiple times. A time delay ensures that the door routine doesn't toggle open/closed repeatedly for one click. I used a static 3s delay in my example but I suppose you could probably retrieve the animation time from the engine and use that instead.

  • 0
  On 14/04/2015 at 23:00, Eric said:

Behavior scripts in Unity are trigged for as long as the input is active so even a quick click on a switch could result in the event firing multiple times. A time delay ensures that the door routine doesn't toggle open/closed repeatedly for one click. I used a static 3s delay in my example but I suppose you could probably retrieve the animation time from the engine and use that instead.

 

Thank you!!! now it kinda makes sense its odd tho,

 

Is all game programming like this?

 

Wouldn't this consume large amounts of pointless CPU cycles?

 

Is it considered normal to have events fire like this?

 

how long is your animation for the door?

 

have you scripted it to that as its opening and its half way (assume 3 secs) and you click it again, does it start closing from the correct animation point.

 

I would assume you would need to code extra code for this... so that its starts the animation from the correct point?

 

PS door looks cool

 

PS re-read it. OK i see the click itself can be fired multiple time while holding it down... now i see why the delay was introduced its not for the animation but for time between allowed clicks...?

  • 0

Well, it's DaveGreen's code, but yes to most of that. The "switch" just looks like a switch. In reality the engine is just detecting the player is colliding with the switch and generating a signal while they're touching. Using the time delay I posted will still cause it to generate the door event as long as you're touching the switch it just doesn't respond to it except every three seconds. It's similar to keyboard "debouncing."

Games do waste CPU cycles. The trick is to get it to a minimum so it runs smoothly. That's why I suggested the timestamp instead of a timer. The timer runs in the background. :)

  • 0
  On 15/04/2015 at 13:43, Eric said:

Well, it's DaveGreen's code, but yes to most of that. The "switch" just looks like a switch. In reality the engine is just detecting the player is colliding with the switch and generating a signal while they're touching. Using the time delay I posted will still cause it to generate the door event as long as you're touching the switch it just doesn't respond to it except every three seconds. It's similar to keyboard "debouncing."

Games do waste CPU cycles. The trick is to get it to a minimum so it runs smoothly. That's why I suggested the timestamp instead of a timer. The timer runs in the background. :)

 

Thanks Eric

This topic is now closed to further replies.
  • Posts

    • I simply don't get why this "OS" exists. Who cares? Great, you can now run a Windows 95-era stupid game, super cool...
    • In the UK the standard edition has been priced at £69.99, the deluxe is £89.99, the super deluxe is .... £119.99 where the hell do they suggest these prices are coming from then! Sorry but at these prices I will not be buying when it comes out. It will be much, much later when the price has dropped considerably!
    • It'll just have $300 dlc instead, several season pass and at every moment you'll be left feeling you purchased the demo by buying the standard or deluxe editions, because the superdeluxe is how they meant to release the game in full.
    • Following higher pricing fears, Take-Two confirms Borderlands 4 won't be $80 by Pulasthi Ariyasinghe Video games going even higher in price has been a controversial subject as of late. Following the bump up to $70 in recent years, which has been vastly adopted by many publishers, now the price is slowly creeping up to be $80 for major releases. However, it seems Take-Two's latest game will not be following this new trend, despite what was being said in earlier reports. Take-Two and Gearbox today confirmed the launch of pre-orders for Borderlands 4, and front and center was the pricing information for the standard edition, which is set at $69.99. It seems the cooperative-focused looter shooter is not following in the footsteps of other high-profile $79.99 releases like Mario Kart World from Nintendo and the upcoming RPG The Outer Worlds from Microsoft. As for why many were expecting the Borderlands title to also be $80, Gearbox boss Randy Pitchford had alluded to the price hike recently. In a social media post in May, Pitchford answered a question from a fan regarding the game possibly being $80, to which he replied, saying that it was not his decision. "If you’re a real fan, you’ll find a way to make it happen," he went on to say, defending a possible $10 price hike. "My local game store had Starflight for Sega Genesis for $80 in 1991 when I was just out of high school working minimum wage at an ice cream parlor in Pismo Beach and I found a way to make it happen." In the end, Borderlands 4 is now confirmed to be releasing at $69.99 for the Standard Edition, with pre-orders available now. At the same time, a $99.99 Deluxe Edition and a $129.99 Super Deluxe Edition have also been confirmed, with each higher tier adding more cosmetic customizations as well as post-launch access to unannounced DLC content. Borderlands 4 launches September 12, 2025, across PC (Steam and Epic Games Store), Xbox Series X|S, and PlayStation 5. A Nintendo Switch 2 release is also planned to land later in 2025.
  • Recent Achievements

    • Explorer
      treker_ed went up a rank
      Explorer
    • Apprentice
      CHUNWEI went up a rank
      Apprentice
    • Veteran
      1337ish went up a rank
      Veteran
    • Rookie
      john.al went up a rank
      Rookie
    • Week One Done
      patrickft456 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      641
    2. 2
      ATLien_0
      274
    3. 3
      +FloatingFatMan
      171
    4. 4
      Michael Scrip
      155
    5. 5
      Steven P.
      140
  • Tell a friend

    Love Neowin? Tell a friend!