Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Instantiate a prefab, then attach script

Discussion in 'Scripting' started by kevdotbadger, Dec 17, 2011.

  1. kevdotbadger

    kevdotbadger

    Joined:
    Sep 13, 2011
    Posts:
    82
    Hello. I have a simple bullet prefab which has a collider and sprite attached. I'm creating it at runtime with

    bul = Instantiate(bullet, new Vector3(transform.position.x + 1, transform.position.y, 0), Quaternion.identity);

    The problem is i don't know which the bullet is suppose to move, so I decided not to attach a script to it.

    Can I attach a script to it at runtime? After I've Instantiate it?
     
  2. kevdotbadger

    kevdotbadger

    Joined:
    Sep 13, 2011
    Posts:
    82
    Basically the issue is my character can walk (and shoot) both ways (left and right). So I need a way of shooting the prefab both ways depending which way he's facing.
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    You can use AddComponent to attach scripts, but there's no reason why you'd need more than one script for this.

    --Eric
     
  4. kevdotbadger

    kevdotbadger

    Joined:
    Sep 13, 2011
    Posts:
    82
    Your're right Eric5h5, I forgot you can access another GameObjects variables if they're declared as global.