1

I have two c# scripts.
One for the cannon:

using UnityEngine;
using System.Collections;

public class CannonScript : MonoBehaviour {

    public GameObject bullet; //bullet object
    public Transform spawnpoint; //spawn point
    float bulletspeed=-3000f; //bullet speed
    public int bullets=10; //number of bullets

    void Update () {
        if ((Input.GetKeyDown ("space") || Input.GetMouseButtonDown(0)) && bullets > 0) {
            GameObject newbullet; //make a new bullet
            newbullet=Instantiate(bullet,spawnpoint.position, spawnpoint.rotation)as GameObject; //instantiate the new bullet
            newbullet.rigidbody.AddForce(spawnpoint.forward * bulletspeed); //add force to the new bullet
            bullets--; //decrease the number of bullets left
        }
    }
}

Another for the UI text on the screen:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class BulletCountScript : CannonScript { //inherit from the CannonScript

    Text text;

    void Start () {
        text = GetComponent<Text> ();
    }

    void Update () {
        text.text = bullets.ToString(); //display the number of bullets
    }
}

When I run it, the UI text on the screen never changes.
I know the CannonScript is working properly, because I can only shoot 10 bullets.
How can I make my UI text display the amount of bullets left?
Am I doing something wrong with inheritance?

1 Answer 1

3

I think you are missunderstanding the inheritance concept. The problem I see is both classes are different instances, so that is the reason because the text is always the same.

To achieve what you want, just do something like this:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class BulletCountScript : MonoBehaviour { 

    public CannonScript cannon;
    Text text;

    void Start () {
        text = GetComponent<Text> ();
    }

    void Update () {
        text.text = cannon.bullets.ToString(); //display the number of bullets
    }
}

Just drag the object who owns the CannonScript to the game object attribute at the BulletCountScript, now, both of them are referencing the same instance.

I hope this helps! Good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

Inheritance can be a double edged sword and often using composition like this is a better and more flexible solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.