- Home /
Using a raycast to disable a component (animator)
I'm making a game that so far uses raycasts to tell where the bullets go. The bad guys all die in one hit, and I would like to have the raycast disable their animators so that they go ragdoll.
The ragdolls accept hits from the raycast and can be pushed all over. But I can't get the raycast to disable the animator.
using UnityEngine;
using System.Collections;public class Shooter : MonoBehaviour {
public float gunPower;
void Update() {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
if (hit.rigidbody != null)
hit.rigidbody.AddForceAtPosition(ray.direction * gunPower, hit.point);
}
}
}
Ok... and how do you expect anyone to help you when you haven't posyted your script?
The script works fine. The question is how to disable a component using a raycast. I didn't think it was important.
I am a bit uncertain what you want with it, but I think this will disable the animator component on the object hit by the raycast.
hit.transform.GetComponent<Animator> ().enabled = false;
Answer by timohausmann · Apr 30, 2015 at 06:44 PM
Hey. You first want to get the GameObject hit by your Raycast. Then get the Animator Component from that object, and finally disable it.
Untested code, but it should work like this:
if (Physics.Raycast(ray, out hit)) {
if (hit.rigidbody != null) {
//get the hit gameObject
GameObject hitObj = hit.transform.gameObject;
//get the Animator Component
Animator anim = hitObj.GetComponent<Animator>();
//disable the Animator Component
anim.enabled = false;
}
}
Answer by Runemark · Apr 30, 2015 at 08:49 AM
Check out this blog post about the transitions between mecanim and ragdoll. http://perttuh.blogspot.fi/2013/10/unity-mecanim-and-ragdolls.html
With raycast you can do something like this (pseudo like code)
if (Physics.Raycast(ray, out hit))
{
// Check if the target is valid
if(hit.transform.GetComponent<MecanimToRagdollScript>() != null)
{
if(<target is mecanim>)
// call mecanim to ragdoll methos
else // if it's already a ragdoll
hit.rigidbody.AddForceAtPosition(ray.direction * gunPower, hit.point);
}
}
Hope it helped.