C# coding help

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.

Two ways to do this, and different reasons for each one.

In script one:

static public Transform target;

Now target can be accessed from any script like this:

Follow.target = this.transform;

I would recommend only using static variables if you’re going to have one “follow” script in the scene.

The second way, which is more code, but also more useful, is this. You don’t need to do anything to your Follow script. But in OtherObject, you have this:

Follow followReference;

void Start() {
followReference = (Follow) Camera.main.GetComponent("Follow");
followReference.target = this.transform;
}

In the second example our extra script has a variable which is going to reference the Follow script. The first line in the Start method finds the Follow component and typecasts (that’s what the (Follow) is), so it’s recognized not only as a component, but a Follow component.

Then our second line assigns the value to the target.

To get a script component on another object in C#, you need to do the following:

EDIT: You do not want to use the string overload of GetComponent as shown above, you want to use the method below when possible. The string version is slower.

MyScript script = myObject.GetComponent(typeof(MyScript)) as MyScrpt;

if (script != null)
{
    script.myPublicVariable = whatever;
}

-Jeremy

Works like a charm. Many thanks to you both.