How to access exposed variables with C#

I want to modify an (exposed) variable in another C# script, analogous to the javascipt example in the “Doing it with code” section in the documentation (Scripting Tutorial.pdf).

I keep getting the following error:

UnityEngine.Component' does not contain a definition for ’

Ok I’ll post an example of what I mean. Suppose I have a GUI (GuiScript) and I want it to set a variable in another script (myScriptB).

using UnityEngine;
using System.Collections;

public class GuiScript: MonoBehaviour
{
   Rect windowRect = new Rect(20, 20, 150, 80);

   void OnGUI()
   {
      windowRect = GUI.Window(0, windowRect, DoMyWindow, "My Window");
   }

   void DoMyWindow(int windowID)
   {
	   Component otherScript = GetComponent(typeof(myScriptB));
	   
      if(GUI.Button(new Rect(10,20,130,20), "Assign Int"))
	  {
		  // **** This where line that produces an error **** 
		  otherScript.myInt = 5; 
	  }
   }
}

It throws an error when I try to access the public varaible myInt (otherScript.myInt = 5;) Here is the script containing the variable I want to modify:

using UnityEngine;
using System.Collections;

public class myScriptB : MonoBehaviour
{

	public int myInt;

	void Awake()
	{
	}

	void Update ()
	{
	}
	
}

Try this:

myScriptB otherScript = GetComponent();

Thanks, using generics worked perfectly :slight_smile:

Yop. np. Another way to do it without generics is to just cast your Component to the more derived type, myScriptB.

myInt is not a property of Component, which is why you were getting the compiler error.