I’m raycasting a beam to select an object. That works. I’ve been able to “extract” the collider name and the picked object’s name (as a string) but I can’t assign the picked object to a variable as a GameObject.
Any ideas?
EDIT: Actually what I’m trying to do is to play an animation on the hit object…
hit.collider.attachedRigidbody.gameObject may get what you want?
EricJ13
September 9, 2009, 8:09pm
3
Here’s a chunk of code from one of my projects that does what I think you’re wanting.
private var cam : Camera;
//////// game object variable
private var myGobj : GameObject;
//////// touch stuff
private var touch : iPhoneTouch;
private var touchRay : Ray;
private var rayHit : RaycastHit;
function Start()
{
cam = Camera.main;
}
function Update()
{
if (iPhoneInput.touchCount > 0)
{
touch = iPhoneInput.touches[0];
touchRay = cam.ScreenPointToRay(touch.position);
switch (touch.phase)
{
case iPhoneTouchPhase.Began:
//////// touching what we want?
if (Physics.Raycast(touchRay, rayHit, Mathf.Infinity))
{
if (rayHit.collider.gameObject.name == "objectNameWeWant")
{
myGobj = rayHit.collider.gameObject;
myGobj.animation.CrossFade("animationWeWant", 0);
//
}
}
break;
case iPhoneTouchPhase.Moved:
//
break;
case iPhoneTouchPhase.Ended:
////////
myGobj.animation.Stop();
break;
}
}
}
Touching the object will start an animation, ending the touch will stop it.
If you have a few different objects that you want to touch and initiate animations you may want to make a tag and tag each one with it, and change
if (rayHit.collider.gameObject.name == “objectNameWeWant”)
to
if (rayHit.collider.gameObject.tag == “objectTagWeWant”)
That way you can trigger animations on things withou worrying about what their names are.
CAVEAT: I’m no Unity veteran so there may be better ways to do it. If so I’m sure others will share.
HTH
myGobj = rayHit.collider.gameObject;
That’s what I needed!
Thanks!