Communication between scripts question(s)

I’m a bit new to programming, started learning about 2 weeks ago, and once in a while I hit a roadblock on something that I know is simple, but yet can’t find documentation for it, or don’t know the proper terminology to find it. So I came here to ask:

Let’s say I have a script that contains something that I want every GameObject to have, the script is called “Health” or something. Inside is something like this:

(this might have syntax errors but it should be understandable what I meant)

var Health=100;
function Alter_Health(O:GameObject,num){
 Health-=num;
 if(Health<=0){
  Destroy(O);
  }
}

If I want every GameObject to have a Health var and able to have the Alter_Health() function called on it, do I need to attach that script as a component to every GameObject?

Isn’t there a way to access something in a script that isn’t attached to any particular GameObject in Unity? Because I want every GameObject to have a Health var and be able to have Alter_Health() called on itself (or any other GameObject)

Thanks. I did search for information on this elsewhere but I think I wasn’t using good terminology.

You could create one script and one gameobject and make that a prefab.

but yes, each gameObject that you want to have health is going to need a script controlling that health…unless…You made a GameHealthUpdater or something like that, that keeps track of all gameObjects health and updates it accordingly.

Depending on the complexity of the GameObjects I would recommend keeping it like the first way.

By ‘the first way’ do you mean the part about ‘create one script and one gameobject and make that a prefab.’?

Does the prefab actually need to have an instance of itself in the scene for me to access vars and functions inside a script on that prefab?

I’ve been reading the manual/reference/etc for a week straight and I’ve read about 200 pages of stuff, and up til today I was doing good with not many obstacles. But today I’m especially confused and am forgetting things. I think I am getting burnt out and maybe need to take a break. Hard to tell.

Thanks for the help

Yes make a prefab :slight_smile:

Why would you want to access vars inside an object that isn’t even instantiated?

For example in one of my games, classic Breakout, There were a ton of bricks that all had the same functionality, but I wanted different bricks to break on different number of hits (hp)

So I created a prefab of a brick attached script and then just adjusted the amount of hp for each brick that I wanted, and each brick kept track of its own hp and if it was destroyed or not.

Make sense? Maybe more info on what exactly your trying to do, I might be able to help more :stuck_out_tongue: