• 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

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

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
  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

    • Kioxia is Toshiba rebranded? Did not know that. 
    • I use to buy only Samsung and Crucial MX but things have change a lot in the last 5 years.   Western Digital Black ssd are very good. Corsair MP too (specially when it comes to gen 5) The Patriot 2TB Viper VP4300 Lite is a good cheap option with decent perf Crucial Txxx is pretty good too. I had bad exp with TeamGroup when they initially came out but i bought two TEAMGROUP T-Force Vulcan Z 2TB SLC Cache for my new computer because they were the cheapest 2 tb with any kind of cache and i've been pleasantly surprised.   You got to do your own research. Does it have dram cache? If yes which type of dram cache. Does it have a large SLC cache? If so how large is it? 20% of the drive? 30% of the drive? For example the TG 2TB i posted above has a 650GB SLC cache which is about 30% of the drive capacity. Is it TLC or QLC. I'd avoid QLC drive without any type of cache unless it's for storage they tend to perform badly with small writes. I'm not an expert so do your own research
    • Exactly my point , 4 Titles that are very popular and also OLD. Cyberpunk 2077 ,Battlefield 2042 , World of Warcraft, Counter-Strike 2. There will also be more that they have not listed. Maybe acceptable from a small developer to have issues with this sort of thing. Not the world's most valuable company.
    • The fact we need to have apps doing this dumb BS is insane. How about not shoving this nonsense down our throats in the first place? I literally know NO ONE that ever said "gee I wish I had a feature that screenshots everything I do on my computer, including sensitive, compromising or heavily private stuff every 2 seconds and neatly catalogs it somewhere on the drive". NO ONE. EVER.
  • Recent Achievements

    • Week One Done
      SmileWorks Dental earned a badge
      Week One Done
    • Community Regular
      vZeroG went up a rank
      Community Regular
    • Collaborator
      Snake Doc earned a badge
      Collaborator
    • Week One Done
      Snake Doc earned a badge
      Week One Done
    • One Month Later
      Johnny Mrkvička earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      580
    2. 2
      ATLien_0
      200
    3. 3
      Michael Scrip
      199
    4. 4
      +FloatingFatMan
      129
    5. 5
      Xenon
      124
  • Tell a friend

    Love Neowin? Tell a friend!