- Home /
Add force to the selected object
Hello Unitians: New to programming so go easy on me! I have the following script attached to my player object. When I left click on a sphere in the world, I want to move the sphere using addForce. Here's my script:
var Layer : LayerMask = 8;
var selection : String;
function Update () {
var fwd = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
Debug.DrawRay(transform.position, fwd * 10, Color.green);
if(Input.GetMouseButtonDown(0)) {
if(Physics.Raycast(transform.position, fwd, hit, 100, Layer)){
selection = hit.collider.name;
Debug.Log("Hit " + selection);
selection.collsion.rigidbody.AddForce(Vector3.up *100);
}
}
}
And Here's the error I'm getting:
NullReferenceException: Object reference not set to an instance of an object
Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.String cacheKeyName, System.Type[] cacheKeyTypes, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory)
Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.Object[] args, System.String
Comment
Answer by G4m3Ninja · Aug 28, 2011 at 04:35 PM
I figured it out. Don't know if this is the right way to do it but it works. I just changed my last line to this:
gameObject.Find("" + selection).rigidbody.AddForce(Vector3.fwd *1000);
Your answer
![](https://koobas.hobune.stream/wayback/20220612193128im_/https://answers.unity.com/themes/thub/images/avi.jpg)