Hi, I am making a 2D game, and I need some help on how to access variables. I am trying to have the camera stop moving when a player collides with an enemy from a separate script, and the problem isn’t the collision, it’s the ability to access a variable from another script that I am having a problem with. I tried searching how but nothing really worked. Here is my script:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class TheRestarter : MonoBehaviour {
public MoveCamera moveCamera;
private Animator anim;
public string GameOverScene;
void Awake () {
anim = GetComponent<Animator> ();
MoveCamera moveCamera = MainCamera.GetComponent<MoveCamera>(); Error ---> "The name 'MainCamera' does not exist in the current context"
moveCamera.speed = 0;
}
void OnCollisionEnter2D(Collision2D target)
{
if(target.gameObject.tag == "Enemy")
{
anim.Play ("RedGiantDeath");
StartCoroutine(DelayedSceneLoad());
}
}
IEnumerator DelayedSceneLoad()
{
yield return new WaitForSeconds(1.5f);
SceneManager.LoadScene(GameOverScene);
}
}
On that script I try to access the “speed” variable from this script:
using UnityEngine;
using System.Collections;
public class MoveCamera : MonoBehaviour {
public float speed = 0.5f;
public float maxSpeed = 0.5f;
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 temp = transform.position;
temp.x += speed * Time.deltaTime;
transform.position = temp;
speed += 0.5f * Time.deltaTime;
if (speed < maxSpeed)
speed = maxSpeed;
}
}
As you can see I have an error saying “The name ‘MainCamera’ does not exist in the current context.”
Could someone please help me?