Rotate object through script on Instantiate object

2019-09-09 20:51发布

I am Instantiating object through script at specific coordinates(x,y,z), and after that i want to rotate it at specific coordinates(x,y,z). here is my code but it doesn't rotating

using UnityEngine;
using System.Collections;
public class Generator : MonoBehaviour {
public GameObject fire;
//public GameObject firetaps;
//System.Random randomize = new System.Random();
// Use this for initialization
void Start () {
    //int fun=randomize.Next(1,6);
    switch (1) {
    case 1:
        PlaceFire();
        break;
    /*case 2:
        PlaceFire1 ();
        break;
    case 3:
        PlaceFire2 ();
        break;*/
      }
     }
    void PlaceFire()
    {
    Instantiate(fire, GeneratedPosition(), Quaternion.identity);
fire.transform.eulerAngles = new Vector3         (275.0941f,287.0612f,72.63131f);// it does not rotate :-(
    //fire.transform.Rotate(275.0941f,287.0612f,72.63131f);
}
Vector3 GeneratedPosition()
{
    float x,y,z;
    x = -142.5f;
    y = 39.165f;
    z =9.9817f;
    return new Vector3(x,y,z);
}

标签: unity3d
1条回答
够拽才男人
2楼-- · 2019-09-09 21:31

You would need to store the return value of Instantiate in your fire field. You never rotated the instantiated gameobject. (also read the edit!!)

Instantiate(fire, GeneratedPosition(), Quaternion.identity);
fire.transform.eulerAngles = new Vector3(275.0941f,287.0612f,72.63131f);

should be

fire = Instantiate(fire, GeneratedPosition(), Quaternion.identity) as GameObject;
fire.transform.eulerAngles = new Vector3(275.0941f,287.0612f,72.63131f);

also your magic values are odd.

edit I just realized fire is your prefab. So you might want to use a local variable instead.

GameObject fireInstance = Instantiate(fire, GeneratedPosition(), Quaternion.identity) as GameObject;
fireInstance.transform.eulerAngles = new Vector3(275.0941f,287.0612f,72.63131f);

Also the 3rd argument of this overload of Instantiate takes a rotation already, so why not pass it there right away?

Instantiate(fire, GeneratedPosition(), Qaternion.Euler(275.0941f,287.0612f,72.63131f));

Idk if you would still need a reference then, depends. But note how it only returns object you will need to cast to the desired type.

查看更多
登录 后发表回答