Dear Community,
I wanted to see if there was a good solution for passing variables to an object that is instantiated. I am creating bullets this way and need to be able to pass in variables to the bullet class which define the direction, type of bullet, and so on based on the current status of the player (two player game). Here is a sample of the code I am using:
using UnityEngine; using System.Collections; public class PlayerFire : MonoBehaviour { public GameObject bullet; // must be assigned in inspector private string playerFire; private PlayerInfo playerInfo; // Use this for initialization void Start () { playerInfo = GetComponent(typeof(PlayerInfo)) as PlayerInfo; playerFire = playerInfo.fire; bullet.player = "player1"; } // Update is called once per frame void Update () { if (Input.GetButtonDown(playerFire)) Instantiate(bullet, transform.position, Quaternion.identity); } }
using UnityEngine; using System.Collections; public class Bullet : MonoBehaviour { float bulletSpeed = 15.0f; // speed of the bullet to travel GameObject cam; // used to ref camera object in order to destroy bullet if it has left the camera view Movement mover; public string player; BoxCollider colBox; // Vector3 bulletPosition; float bulletDirectionX; float bulletDirectionY; // Use this for initialization void Start () { bulletPosition = new Vector3(0, 0, 0); mover = GameObject.Find(player).GetComponent(typeof(Movement)) as Movement; cam = GameObject.Find("Main Camera"); colBox = GetComponent(typeof(BoxCollider)) as BoxCollider; bulletDirectionX = mover.fireDirectionX; bulletDirectionY = mover.fireDirectionY; } // Update is called once per frame void Update () { //move bullet //check for collision //check for leaving view bulletPosition.x = bulletDirectionX*Time.deltaTime*bulletSpeed; bulletPosition.y = bulletDirectionY*Time.deltaTime*bulletSpeed; colBox.transform.Translate(bulletPosition); } void OnBecameInvisible () { Destroy(gameObject); } void bulletDestroy() { Destroy(gameObject); } void OnCollisionEnter(Collision objHit) { if(objHit.gameObject.tag == "enemy" ){ Destroy(objHit.gameObject); } } }
The final solution that I want to avoid is creating two bullet classes so that each player has their own and it pulls from that.
Zweegie