Accessing a property from a Transform

Hi guys, quick question.

Im using c#.

I have a script that searches the map for a bunch of transforms, sorts them according to distance and selects the closest one as the target, assigning the closest one as “SelectedTarget”

I need to get the “mass” property attatched to “SelectedTarget” so I can let the AI decide if it will chase “SelectedTarget” or run away. I have been at this for hours, any help would be greatly appreciated. Thanks in advance!

Here’s my code:

public class PredatorScript : MonoBehaviour {

public float mass = 1;
public float size = 1;

public List<Transform> FoodTargets;
public Transform SelectedTarget;
private Transform myTransform;
Transform target;
public float speed = 1;
public float sight = 1;
private float distance = 0;
private int counter = 0;

void Start () {
	
	FoodTargets = new List<Transform>();
	SelectedTarget = null;
	myTransform = transform;
	
	AddAllFood ();
	
}

public void AddAllFood()
{
	
	GameObject[] Foods = GameObject.FindGameObjectsWithTag("Herbivore");
	
	foreach (GameObject enemy in Foods)
		AddTarget (enemy.transform);
	
}

public void AddTarget(Transform enemy)
{
	FoodTargets.Add (enemy);
}


private void SortTargetsByDistance()
{
	FoodTargets.Sort (delegate(Transform t1, Transform t2) { 
		return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));
	});
}

private void TargetEnemy()
{
	if (SelectedTarget == null) {
		SortTargetsByDistance ();
		SelectedTarget = FoodTargets [0];
	} 
	else {
		SortTargetsByDistance ();
		SelectedTarget = FoodTargets [0];
	}
}

void Update(){
	
	TargetEnemy ();

	
	distance = Vector3.Distance(transform.position, SelectedTarget.transform.position);

	mass = SelectedTarget.trasform.mass; <------- This is what i've been trying
	
	if (distance < sight) 
		
	{
		transform.LookAt (transform.position + new Vector3 (0, 0, 1), transform.position - SelectedTarget.transform.position); //Face target
		transform.Translate (Vector3.down * speed * Time.deltaTime); //movement forwards
		
	}
	
	else {
		
		if (counter >= 120){
			transform.Rotate(0, 0, Random.Range(0, 360));
			counter = 0;
		}
		
		transform.Translate (Vector3.down * (speed/3) * Time.deltaTime);
		counter++;
		
	}

Hey. Firstly, SelectedTarget is of type Transform which inherits the property rigidbody. I’m guessing you want the mass property of the rigidbody? If so you can call either:

mass = SelectedTarget.ridigbody.mass;
mass = SelectedTarget.GetComponent<RigidBody>().mass;

If “mass” is a property of another custom script, you can use the second example to access the component. For example, if you have a component called PreyScript you could access its variables/properties like so:

PreyScript prey = SelectedTarget.GetComponent<PreyScript>();
if(prey)
{
    mass = prey.mass;
}
else
{
    Debug.Log(string.Format("No PreyScript on '{0}'", SelectedTarget.name); 
}