- Home /
Raycast Collision - Getting Custom Values from GameObject
So, I think this could be an extension of this question:
http://answers.unity3d.com/questions/141529/getting-gameobject-from-raycast-hit.html
Anyway, using Raycasts, I need to get the following information from the GameObject:
*Is a vehicle (simple boolean value)
*What type of sound to play when walking on (GameObject possibly, but grass, concrete, metal, etc.)
I'd prefer to not have to give values for each GameObject in the map. If a value isn't found, assume False for the first set and nothing for the second. Any suggestions on how I can go about doing this?
Thank you much!
Answer by aldonaletto · Apr 04, 2012 at 11:51 AM
You can create a simple script and attach it to the game objects of interest, then set the variables in the Inspector. When hitting the object, get this script and read its variables.
The script attached to the objects could be something as short as this (let's call it Variables.js):
enum Mat {Nothing, Metal, Grass, Concrete, Stone}; // possible materials
var vehicle: boolean = false; // change this in the Inspector, if necessary var myMat: Mat = Mat.Nothing; // select the material in the Inspector To get these values from a hit object, do the following:
... if (Input.GetMouseButtonDown(0)){ var hit: RaycastHit; var ray: Ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, hit)){ // if some object hit... // try to get its Variables script: var values: Variables = hit.transform.GetComponent(Variables); if (values){ // if the object has the script Variables attached... var isVehicle: boolean = values.vehicle; // read the variables var mat: Mat = values.myMat; } else { // but if it doesn't have the script... isVehicle = false; // assume the default values mat = Mat.Nothing; } } } ...
Your answer
Follow this Question
Related Questions
Grabbing MonoBehavior object from collision 1 Answer
Send Message On Collision 1 Answer
Layered Collisions 1 Answer