So, I have PlayerController scirpt like in the Roll-a-Ball tutorial (modified to 2D, and full of other things)
It has a score system too, it works fine, adds +1 point when colliding with objects.
I managed to put a gun on my character, it spawns bullets from a prefab using Instantiate.
I need to get +10 score when the bullet collides with an object. I attached a scirpt to my bullet
prefab, what do I should write in?
Here is the full PlayerController script:
public class LP_PlayerController_2 : MonoBehaviour {
public float speed;
public float speed2;
public GameObject bulletPrefab;
public GameObject boxPrefab;
public Transform BulletSpawn;
public Transform BoxSpawn;
public GameObject halfboxPrefab;
public GameObject reflectorPrefab;
public GameObject workingrefPrefab;
public Text scoreText;
private Rigidbody2D rb;
private int score = 0;
void SpawnWorkingRef () {
var workingref = (GameObject)Instantiate (
workingrefPrefab,
BoxSpawn.position,
BoxSpawn.rotation);
Destroy (workingref, 25.0f);
}
void SpawnReflector () {
var reflector = (GameObject)Instantiate (
reflectorPrefab,
BoxSpawn.position,
BoxSpawn.rotation);
Destroy (reflector, 25.0f);
}
void SpawnHalfBox () {
var halfbox = (GameObject)Instantiate (
halfboxPrefab,
BoxSpawn.position,
BoxSpawn.rotation);
Destroy (halfbox, 30.0f);
}
void Fire() {
var bullet = (GameObject)Instantiate (
bulletPrefab,
BulletSpawn.position,
BulletSpawn.rotation);
bullet.GetComponent().velocity = bullet.transform.up * speed2;
Destroy (bullet, 7.5f);
}
void SpawnBox() {
var box = (GameObject)Instantiate (
boxPrefab,
BoxSpawn.position,
BoxSpawn.rotation);
Destroy (box, 30.0f);
}
void RotateLeft () {
rb.transform.Rotate (0, 0, -1200 * Time.deltaTime);
}
void RotateRight () {
rb.transform.Rotate (0, 0, +1200 * Time.deltaTime);
}
void Start () {
rb = GetComponent();
score = 0;
SetScoreText ();
}
void FixedUpdate () {
float MoveHorizontal = Input.GetAxis ("Horizontal");
float MoveVertical = Input.GetAxis ("Vertical");
Vector2 movement = new Vector2 (MoveHorizontal, MoveVertical);
rb.AddForce (movement * speed);
if (Input.GetKeyDown (KeyCode.Mouse0)) {
Fire ();
}
if (Input.GetKeyDown (KeyCode.Alpha1)) {
SpawnBox ();
}
if (Input.GetKeyDown (KeyCode.Alpha2)) {
SpawnHalfBox ();
}
if (Input.GetKeyDown (KeyCode.Alpha3)) {
SpawnReflector ();
}
if (Input.GetKeyDown (KeyCode.Q)) {
RotateLeft ();
}
if (Input.GetKeyDown (KeyCode.E)) {
RotateRight ();
}
if (Input.GetKeyDown (KeyCode.Alpha4)) {
SpawnWorkingRef ();
}
}
void OnCollisionEnter2D (Collision2D other) {
if (other.gameObject.CompareTag ("Box")) {
score = score + 1;
SetScoreText ();
}
if (other.gameObject.CompareTag ("Small Brick")) {
score = score + 1;
SetScoreText ();
}
if (other.gameObject.CompareTag ("Half Box")) {
score = score + 1;
SetScoreText ();
}
}
void SetScoreText () {
scoreText.text = "Score: " + score.ToString ();
}
}
Thanks for the answers!
↧