Reputation: 13
I have this code below, but I get an error and can't fix it. The error:
The name
script
does not exist in the current context.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowCube: MonoBehaviour
{
public GameObject cube;
public Vector3 cubePov;
public Vector3 cubePovStart;
public Vector3 camPov;
void Start()
{
cube = GameObject.Find("Cube");
CollisionDetection script = cube.GetComponent<CollisionDetection>();
}
void Update()
{
cubePov = (GameObject.Find("Cube")).transform.position;
camPov = transform.position;
if (script.CollisionDown == true)
{
}
}
}
How do I fix it?
Upvotes: 1
Views: 5213
Reputation: 60
Variables declared inside methods can not be used in other methods. You are declaring script
in Start()
, but trying to use it in Update()
. Just make it a global variable (a.k.a declare it on the top of your code) and you should be good to go!
Upvotes: 0
Reputation: 4288
So what that means is, the variable 'script' hasn't been declared in the Update()
method. You're declaring 'script' in the Start()
method. If you need it to be available to both declare it up next to the "public Vector3" and then both locations can access it. But do note, if you declare it, it has to be set to something before it can be used still. In the below, I moved its scope so both can access it.
Again to reiterate, Start()
must be called before Update()
otherwise a null exception will occur because you initialize it (set it to something) in Start()
.
I'm not well versed in Unity but if there is any chance that GameObject.Find
might return a null object if what you're asking for is not found then you would want to put a check in to handle that or at least be aware of it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowCube : MonoBehaviour
{
public GameObject cube;
public Vector3 cubePov;
public Vector3 cubePovStart;
public Vector3 camPov;
public CollisionDetection script;
void Start()
{
cube = GameObject.Find("Cube");
script = cube.GetComponent<CollisionDetection>();
}
void Update()
{
cubePov = (GameObject.Find("Cube")).transform.position;
camPov = transform.position;
if (script.CollisionDown == true)
{
}
}
}
Upvotes: 2
Reputation: 3057
script
exists just in Start()
method; so that' why it is not visible in the Update()
method. Declare it globally, and then reuse it (in case if those are static class methods).
Upvotes: 3