- Home /
How do I get string name from a script on a rayhit gameobject?
I have a script that raycasts an area infront of a tiny ship that reads molecules(gameobjects).
I have made 2 script for this, but I don't know how to make the first script get the string from the script(MoleculeNametag.js) of the gameobject it's hitting.
--(MoleculeNameDisplayer.js)---------------------
#pragma strict
static var Name : String;
function Update()
{
Debug.DrawRay(transform.position, transform.forward, Color.red, 10);
var hit : RaycastHit;
if (Physics.Raycast(transform.position, transform.forward, hit, 10)){
Name = hit.collider.gameObject.name; <----(This is what I don't know what to do with)
}
}
--(MoleculeNametag.js)---------------------
#pragma strict
var NameOfMolecule : String;
Does anyone know how I can achieve this? Or am I not explaining my problem clearly?
Answer by Huacanacha · Jun 12, 2014 at 04:55 AM
Here it is in C#:
MoleculeNametag molecule = hit.collider.gameObject.GetComponent<MoleculeNametag>();
if (molecule != null) {
Name = molecule.NameOfMolecule;
}
And here is the docs reference for GetComponent which has JS/Unityscript examples. Looks like it would be "gameObject.GetComponent(MoleculeNametag)" in JS;
No problem ;)
Note that if you have other colliders in your scene you can use Layers to ensure you only ever 'hit' a molecule. To do this create a new physics collision layer, then use a Raycast method that accepts a Layer$$anonymous$$ask... Raycast will then only return a hit on the layers you specify. Layer$$anonymous$$asks are easy to setup via the inspector (i.e. if you have a public Layer$$anonymous$$ask field on your script) but a little painful to do via code.
Your answer
![](https://koobas.hobune.stream/wayback/20220613151340im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Displaying name of currently focused object. 3 Answers
Raycasts ignoring colliders based on Collider Name 2 Answers
Get object name from raycast. 1 Answer
Show variable name from a class as String 2 Answers
How do I retrieve Mecanim State Name? 2 Answers