- Home /
Getting a script variable one frame too late?
I have a shield attached to my character. The shield's variable will check if the shield has collided with a monster (detect = true). My character will check if the shield has collided with a monster (shieldScript.detect == true), but it's always a frame too late.
I always get false, then true. So i dies and only after I'm protected...
using UnityEngine;
using System.Collections;
public class collisionDetect : MonoBehaviour {
public bool detect = true;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (detect != true){
detect = false;
}
}
void OnCollisionStay2D(Collision2D other){
if (other.gameObject.tag == "monstre") {
detect = true;
}
}
}
`
Then this is my character script.
public GameObject shieldObject;
public collisionDetect shieldScript;
if (shieldScript.detect == false) {
What should I do?
Problem seems to be that your using OnCollisionStay2D, which is only triggered once an object has already been in your collider for a frame before.
Try using OnCollisionEnter2D()
http://docs.unity3d.com/ScriptReference/$$anonymous$$onoBehaviour.OnCollisionStay2D.html http://docs.unity3d.com/ScriptReference/$$anonymous$$onoBehaviour.OnCollisionEnter2D.html
Answer by FortisVenaliter · May 18, 2015 at 06:16 PM
In project settings, go to the "Script Execution Order". Make sure the shield script is executed before the player script each frame.
Answer by fafase · May 18, 2015 at 06:32 PM
Record the states and perform the actions in LateUpdate. Changing the order could be a solution. In my experience, it solves one problem and creates another somewhere. Also, it makes debugging more cumbersome since you need to consider code you do not have in front of you and will come the time when you forgot about it.
Doing it all in LateUpdate is clear as it tells explicitly when and what happens.
Thanks for your answer.
They are all working! but OnCollisionEnter is the best for the moment (LateUpdate () make my game slower and Script Execution Order might work but I want a good debugging).
I also changed my FixedUpdate () to Update ().
Your answer
Follow this Question
Related Questions
About animation! 0 Answers
show video frame on texture in ios 1 Answer
How to make One Arm Bandit? 1 Answer
Blend tree like effect on one animation ? 0 Answers
How to Render and Blend Multiple Frames to a Buffer in Unity? 0 Answers