Accessing variables from a class on another GameObject

I’m trying to change a variable in a class from another game object, but I can’t seem to figure out how.

For example, let’s say I want to change the maxForwardSpeed variable of the CharacterMotorMovement Class from another script, on another game object. How would I access it and change the speed.

Hope this makes sense. Thanks!

this one should do it:

C#

SomeScript ss = (SomeScript)GameObject.GetComponent(typeof(SomeScript));

ss should now be accessible as long as your class is public/internal or protected in an inherit, so if SomeScript have a field called Speed just do this:

C#

ss.Speed = someValue;

This is my code in javascript… gernadeScript.js

function AddGernade() {

	var playerScriptRequest = GameObject.Find("Player");
	
	var playerScriptFunction = playerScriptRequest.GetComponent("PlayerScript");
	
		playerScriptFunction.inventory

}

I’m trying to access the variable timeGernades within the Inventory Class in PlayerScript. I’m stuck on inventory, don’t know how to access a variable within Inventory.

This is what the class looks like in the PlayerScript.js

class PlayerInventory {

	var timeGernades : int;

	var fragGernades : int;

}

var inventory : PlayerInventory = PlayerInventory();

Never set my self into unity scripting, don’t find it really useful at all, since C# is more commonly used and a bit faster to compile etc…

But there is some converters on the internet so try to use those?

I’ve been considering working with C# as well, but I got so used to Unity Script, JavaScript or whatever you want to call it.

Thanks for the help by the way. I found a work around, but not a direct answer to my question:

I wrote a function that access a function on the PlayerScript…which than gets access to the variable within the class locally.

I wouldn’t like to rely on local functions only, I’d love to access the variable within the class directly. I’ll figure it out… :stuck_out_tongue:

GernadeScript.js access PlayerScript.JS

function AddGernade() {
    
    var pScript : PlayerScript = GetComponent(PlayerScript);
    
    pScript.AddTimeGernade();

		 

}

PlayerScript.js

class PlayerInventory {

	var timeGernades : int;

	var fragGernades : int;

}

var inventory : PlayerInventory = PlayerInventory();


// Add Gernade Funcation

function AddTimeGernade() {

	inventory.timeGernades = 2;

}

Hi Moonpix,

There are two problems with your code.

The first is that you have to tell Unityscript to make a variable accessible to other scripts. It doesn’t do it automatically. You need to change your “PlayerScript” as follows:

class PlayerInventory {

	public var timeGernades : int;

	public var fragGernades : int;

}

var inventory : PlayerInventory = PlayerInventory();

That should make the class accessible from your other scripts.

The second problem is that you’ve spelled “G__r__enades” wrong! :slight_smile: