- Home /
RigidBody.It doesn't give speed to my gameObject
This script in my opinion should've given some volocity to my gameobject onEnable, however he just appears befeore the camera and fall down.Can anyone help me with that problem?
using UnityEngine;
using System.Collections;
public class BulletProperties : MonoBehaviour
{
public float BulletSpeed = 10000;
void OnEnabled()
{
gameObject.rigidbody.velocity = new Vector3 (0, 0, BulletSpeed);
}
void OnCollisionEnter(Collision col)
{
this.gameObject.SetActive (false);
}
}
If the object is affected by gravity, it will fall. If the falling is fast enough, relative to the forward speed, you might not notice that it IS moving forward. You can turn off "use gravity" for the rigid body, to test.
Answer by Bodaciouslycrazy · Jul 13, 2016 at 08:47 PM
try using the Start() function instead of OnEnabled. Start is always called when a new object is instantiated, but OnEnabled is not called, because the "enable" property wasn't changed. It was always enabled.
Try this!
public float BulletSpeed = 10000;
void Start()
{
gameObject.rigidbody.velocity = new Vector3 (0, 0, BulletSpeed);
}
The problem is I am using (object pooling);Which is done in other script, Everything works fine except the movement of the object. As I understood OnEnabled() is similar to Start().The difference is that Start() is called once when the object is created and OnEnabled()is called everytime gameObject is SetActive(true).
Answer by matioma · Jul 14, 2016 at 08:55 AM
Thanks guys for help.I found the solution myself.Actualy I don't know why it didn't work that way but I copied
gameObject.rigidbody.velocity = new Vector3 (0, 0, BulletSpeed);
In this script
'public GameObject bulletType; public int numberOFBullets;
public float timeBetweenShots;
private float timeBetweenShotsRef;
private List<GameObject> objectPoolingList = new List<GameObject>();
void Start ()
{
timeBetweenShotsRef = timeBetweenShots;
for (int i=0; i < numberOFBullets; i++)
{
GameObject obj = (GameObject)Instantiate(bulletType);
obj.SetActive(false);
objectPoolingList.Add(obj);
}
}
void Update ()
{
timeBetweenShotsRef -= Time.deltaTime;
Debug.Log (timeBetweenShotsRef);
if (Input.GetMouseButtonDown (0) && timeBetweenShotsRef < 0f)
{
BulletSetActive();
timeBetweenShotsRef = timeBetweenShots;
}
}
void BulletSetActive()
{
for (int i=0; i< objectPoolingList.Count; i++)
{
if(!objectPoolingList[i].activeInHierarchy)
{
objectPoolingList[i].transform.position = transform.position;
objectPoolingList[i].transform.rotation = transform.rotation;
objectPoolingList[i].SetActive(true);
objectPoolingList[i].gameObject.rigidbody.velocity = new Vector3 (0, 0, 10); // pasted code
break;
}
}
}
And It worked.
If someone knows the reason why it doesn't work the way I've written first time will be happy to get the answer.
Answer by _Yash_ · Jul 14, 2016 at 12:55 PM
It was a typo.
you wrote void OnEnabled()
it should be void OnEnable()