Hello everyone. I have been programming with Unity for a few weeks, but I keep encountering roadblocks when it comes to using C# with Unity. I have a couple of questions that I was wondering if anyone would be able to answer.
My first question involves changing an exposed variable in another script by using one of my own C# scripts. I have come up with an example of the concept that I am having trouble with. Say I have this code attached to my main camera:
using UnityEngine;
using System.Collections;
public class Follow : MonoBehaviour {
public Transform target;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.LookAt(target);
}
}
Now suppose that I want to change the value of target from another script attached to a separate object, how would I go about doing this? I have seen the javascript examples where a variable without a type is used to retrieve the script using GetComponent. Can this also be done using C#? I have tried using GetComponent in another script similar to what follows:
public class OtherObject: MonoBehaviour {
void OnMouseDown(){
Camera.main.GetComponent("Follow").target = this.transform;
}
}
When I try to use this line of code, I get the error message UnityEngine.Component' does not contain a definition for
target. Am I close to getting this to work?
My second question is similar to the first, but I would like to know how to read the value of a public variable that is stored in a script attached to another object. Thanks in advance to anyone who can help.