How can I get this code to recognize coll in my update function?
using UnityEngine; using System.Collections;
public class Ninja : MonoBehaviour {
float speed = 7.0f;
// Use this for initialization
void Start () {
transform.position = new Vector3 (2, 8, -5);
}
// Update is called once per frame
void update () {
if (coll.collider == false & Input.GetKey (KeyCode.UpArrow)) {
Debug.Log ("up");
}
}
void faceRight () {
transform.localRotation = Quaternion.Euler (0, 0, 0);
}
void OnCollisionStay2D(Collision2D coll){
// If the Collider2D component is enabled on the object we collided with.
if (coll.collider == true) {
if (Input.GetKey (KeyCode.LeftArrow)) {
Debug.Log ("left arrow");
transform.position += Vector3.left * speed * Time.deltaTime;
}
if (Input.GetKey (KeyCode.RightArrow)) {
Debug.Log ("right arrow");
transform.position += Vector3.right * speed * Time.deltaTime;
}
}
}
}
Can you describe the problem? It's pretty hard to diagnose and help when we don't know the problem.
Why is the Update function written with a lower case u? ("update")?
Why are you using a variable "coll" in update when it is only defined in OnCollisionStay2D?
Sorry for any errors or sloppiness. I'm fairly new and trying to learn. But yeah, so my goal here is to apply new physics to my sprite only when the following conditions are met; $$anonymous$$y sprite is not touching anything and up arrow is held. I just want to figure out how to get my update function to tell that it's not touching anything.
Answer by FortisVenaliter · May 04, 2016 at 05:56 PM
Okay, so the problem here is called Scope. There are a bunch of articles you can look up online if you use that keyword, but here's a basic breakdown:
Variables ONLY exist within the block that they are defined. In your case, the coll variable is defined in the OnCollisionStay2D function as a parameter, so it can't be accessed in any other function. If you need to use it in the update function, you need to cache it off as a class-scope variable (like your speed float), which will allow it to be accessed from any function in that class. But keep in mind class variables are persistent with the instance, so if you set it in the OnCollisionStay2D function, it will stay set, and will not revert to null when there isn't a collision, so you'll have to handle un-setting it too.
Your answer
Follow this Question
Related Questions
Encyclopedia System 1 Answer
Monodevelop Problem 5.5.2 0 Answers
How do I change a sprite opacity over time? 0 Answers
You know the drill: my shoot script isn't working (again.) 2 Answers
Any way to set custom curves on an AudioSource in Webgl ? 0 Answers