- Home /
Select a random GameObject (Rain) (C#)
How can I do a custom script to random detect and select a GameObject with the aspect "Point" ?
I'm using Rain Indie and I want to create the custom script in C#.
Hope someone knows how to do that.
Answer by Tomer-Barkan · Oct 17, 2013 at 09:51 AM
You could create an array of possible GameObject
s, and select one from it randomly using the following code:
public class MyClass : MonoBehaviour {
public GameObject[] possibleChoices = new GameObject[0];
public GameObject getRandomGameObject() {
return possibleChoices[Random.Range(0, possibleChoices.Length)];
}
}
just be sure to populate possibleChoices
with the GameObjects you want to be available in the inspector.
Okay here's my custom script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using RAIN.Core;
using RAIN.Action;
public class select : RAIN.Action.Action
{
public select()
{
actionName = "select";
}
public override RAIN.Action.Action.ActionResult Start(RAIN.Core.Agent agent, float deltaTime)
{
RAIN.Sensors.Sensor.FocusOn("Point");
return RAIN.Action.Action.ActionResult.SUCCESS;
}
public override RAIN.Action.Action.ActionResult Execute(RAIN.Core.Agent agent, float deltaTime)
{
RAIN.Sensors.Sensor.GetObjectsWithAspect("Point");
return RAIN.Action.Action.ActionResult.SUCCESS;
}
public override RAIN.Action.Action.ActionResult Stop(RAIN.Core.Agent agent, float deltaTime)
{
return RAIN.Action.Action.ActionResult.SUCCESS;
}
}
How can I now select just one point and save this in a variable ?
Create a game object called "$$anonymous$$yObj" and attach it to my script (called myClass). Assign the possible GameObjects that you want to randomize in possibleChoices using the inspector.
Then add in your code a variable of type GameObject that will hold your randomly selected object:
private GameObject randomObj;
Then select a random game object and assign it to the new variable
randomObj = GameObject.Find("$$anonymous$$yObj").GetComponent<$$anonymous$$yClass>().getRandomGameObject()