- Home /
Linking object functions
I am creating a game which requires one object to perform a specific action when another (random) object performs the same action. Is it possible (using C#) to create two way communication between objects using handlers or the like?
In other words, when I rotate Object A by 90 degrees, Object B also rotates 90 degrees but in another scenario, it may be that when Object A is rotated 90 degrees, it's Object C that's required to rotate 90 degrees, and not Object B.
I hope I've made clear what I'm trying to accomplish.
O$$anonymous$$, I think I've sorted it, unless anyone has a better solution. What I have done is to create a list on the source object which the target object adds itself to if a link is required. Then, when the source object carries out the specific action, it iterates through the list and sends a function call back to all target objects.
Answer by SkaredCreations · Dec 14, 2014 at 05:23 PM
You could for example store the list of the objects in a script and when you need to get another random object use a function from there.
For example:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ObjectsList : MonoBehaviour {
public static ObjectsList instance;
// Drag all the available objects here from hierarchy panel
// or else use FindObjectsOfType<YourScriptName>() in Awake or Start
public GameObject[] allObjects;
void Awake () {
instance = this;
}
public GameObject GetRandomObject (GameObject excludeMe) {
List<GameObject> list = new List<GameObject>(allObjects);
list.Remove(excludeMe);
return list[Random.Range(0, list.Count)];
}
}
Then in your script attached to the object you'll call the following line and apply your rotation or everything else to it:
GameObject randomObject = ObjectsList.instance.GetRandomObject(gameObject);
Yeah, that's what I have ended up doing (as per my comment in my original post); for now anyway. I just don't like "answering" my own questions, so you get the credit ;)
Your answer
Follow this Question
Related Questions
Best practice for object communication 3 Answers
creating a linked object mesh 0 Answers
Two-way communication between parent and children-objects 1 Answer
Find Script from another script 2 Answers
how to link 1 var between 2 scripts ? 2 Answers