简体   繁体   中英

Problems with rigidbody2D in unity

I honestly can't figure out what's wrong with this code. I guess I'm still new at unity, would love to get some help.

void Start()
{
    GameObject objToSpawn;
    objToSpawn = new GameObject("Obstacle");
    objToSpawn.AddComponent<Rigidbody2D>();
    objToSpawn.AddComponent<BoxCollider2D>();
    objToSpawn.AddComponent<SpriteRenderer>();
    Rigidbody2D rigid;
    rigid = GetComponent<Rigidbody2D>();
    rigid.gravityScale = 0;
    rigid.isKinematic = true;
    pos = objToSpawn.transform.position;


}

When the program starts, the gravity scale is still 1 and isKinematic is still false. Why?

The other answer is correct. You should use a prefab and instantiate it when you have a complex object. I'll explain why the code you have doesn't work though too. your error is in the line

rigid = GetComponent<Rigidbody2D>();

This will get the rigidBody2D of the GameObject that the current script is attached to. I'm guessing what you meant to do was:

rigid = objToSpawn.GetComponent<Rigidbody2D>();

Which will get the rigidBody2D that is on the object you just instantiated called objToSpawn .

I advise you to create a prefab then instantiate it. It would be a better way to create a new object than the one you are doing. Go to unity documentation and check its parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM