Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

problem grabbing a script from an instantiated object.

Discussion in 'Editor & General Support' started by The_Raz, May 20, 2014.

  1. The_Raz

    The_Raz

    Joined:
    Feb 8, 2014
    Posts:
    79
    Below is the part of my script I am having trouble with.

    at bulletscript speed = bulletspeed; I am getting an error that there is no reference, but right above I created the reference to the new object as it got instantiated. What am I doing wrong that is keeping the reference from being grabbed?

    if(Input.GetMouseButton (0))
    {
    if(howlongtoshoot < Time.time)
    {
    Bullet bulletscript = Instantiate(bullet,transform.position,transform.rotation) as Bullet;
    bulletscript.Speed = bulletspeed;
    bulletscript.Drop = bulletdrop;

    howlongtoshoot = Time.time + firerate;
    }
    }
     
  2. The_Raz

    The_Raz

    Joined:
    Feb 8, 2014
    Posts:
    79
    okay well apparently problem is that the object is not 'built' yet when you instantiate it and so you cannot change the values you want to change. Instead I am going to attempt to have the script identify who instantiated it and grab the values from them.
     
  3. TrentNaylor

    TrentNaylor

    Joined:
    Apr 22, 2014
    Posts:
    27
    I might suggest making use of gameObject.GetComponent. So if you bullet prefab has a script called "Bullet" attached, then you could do something like.

    //Assign your bullet prefab

    GameObject bullet;

    //Instantiate the gameObject first (your bullet prefab)

    GameObject myNewBullet = Instantiate(bullet,transform.position,transform.rotation) as GameObject;

    //Then you can change the values of the attached script on your new gameObject

    myNewBullet.getComponent<Bullet>().Speed = bulletspeed;
    myNewBullet.getComponent<Bullet>().Drop = bulletDrop;