Access class variables of selected object

Hi all,

I am trying to make a space-based RTS game. So there will be multiple ship types, each with it’s own variable values, but the same number and type of variables for each ship type. I’ve got the scripts set up the way I want them, but I’m stuck at the last step, which is accessing the variables of an object I select in a scene. Including a little bit more code than necessary so you can see where I put the code I’ve entered.

ShipObjDefTest.js - Ship variables definition. Attached to the camera for now.

#pragma strict

public class ShipObj {
	var type : String;
	var size : String;
	var speed : float;
	var cost : float;
}

function Start () {
}

function Update () {
}

TestScout.js - Values for this ship type. This is attached to a prefab of the same name.

#pragma strict

var newShip = new ShipObj();
newShip.type = "Scout";
newShip.size = "Small";
newShip.speed = 30;
newShip.cost = 100;

function Start () {
}

function Update () {
}

QuickShipPicker.js - My testing script. Attached to the camera.

#pragma strict

var hitinfo : RaycastHit;
var ship;

function Start () {
}

function Update () {
	if (Input.GetMouseButtonDown(0)) {
		var cameraRay : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		if (Physics.Raycast (cameraRay, hitinfo)) {
			ship = hitinfo.transform.parent;
			print(ship);
			//print(TestScout.newShip.type);
			//print(TestScout.newShip.speed);
		}
	}	
}

The commented lines in QuickShipPicker.js show what I want to do, but the type of ship (TestScout in the commented lines) will not always be the same.

Any help is much appreciated!

You’ll have to use a GetComponent in your raycast stuff to get the script from the object you’re hitting and access it.

e.g.

if(Physics.Raycast(ray, hit)){
   var ship : GameObject = hit.collider.gameObject ;
   var shipScript : TestScout ;
   shipScript = ship.GetComponent(TestScout) as TestScout ;
   Debug.Log(shipScript.shipVariable.classVariable) ;
}

…something along those lines.