Change/asssign a variable in a script, through an event

How can I assign an unassigned variable only when something happens?
Ex: I want to change the variable X into a selected game object. Object A will detect if Object B is in range, so A will change the X variable into Object B, but only after he is detected or in range.



There are two things you need to do here:

(1) Object A needs a reference to Object B so it can detect when Object B is close enough

(2) Object A needs to know how to detect if Object B is close enough

There’s a few ways to do (1). The best way is to use a public field to link Object B to Object A in the editor. You do this by putting this in a script (let’s call that ObjectAScript for now, you can change all the names to something sensible when you do it):

public GameObject otherObject;

and put that script on Object A. This will put a field named Other Object in Object A’s inspector. You can then drag Object B from the hierarchy to this field, or click the icon next to it and choose from all gameobjects in the scene (which does let you search by name to filter).

So that’s (1) dealt with. For (2), detecting how close Object B is, we’ll use the Update function, which is called up to 60 times per second for each script component on a gameobject, and is very useful. Another useful thing is the Vector3.Distance function, which we can use to find the distance between two objects, so we’ll put that in our Update function to continually check the distance.

public GameObject otherObject;
public float searchRadius; // set the search radius in the inspector
	// alternatively: public const searchRadius = 0.5F; etc
void Update()
	if (Vector3.Distance(this.transform.position, otherObject.transform.position <= searchRadius)
		// do stuff here

If you haven’t done so already, I suggest reading through the documentation on scripting in unity, especially the sections on controlling gameobjects and components via scripts for more information on this subject.