- Home /
Attaching a "Mass" variable to all or most gameObjects and how to access them
So I'm making a simple game where you move around and eat things smaller than you. I would like to attach a simple variable to game objects to give them a "mass" and check to see that if they are smaller than you then you can eat them etc.
But since each object will have a different mass, how can I add a simple script that I can change depending on who it is on? And then I need to check the players mass against the gameObjects mass.
You don't have to write the script yourself unless I am overcomplicating it, I have no problem reading tutorials I just don't know where to begin.
Thanks in advance!
Answer by Lysander · Jan 01, 2018 at 09:09 PM
Just make a new MonoBehaviour (called Status or something), add a public float variable to it called "mass", and then set its value in the inspector, or through code. If you're generating objects to eat, then the spawner is likely going to be the object that decides what new objects get what mass value assigned (and there should be a corresponding scale difference between spawned objects to reflect this).
The rest is just a matter of how you consume objects- if it requires a button press, then on button press you can raycast directly ahead of the player, see if there's an object with a "Status" component right in front of you by using GetComponent, and then check the mass value on that component against the player's mass.
Alternatively, you can do it based on trigger areas. This is how Spore works in the "microscopic organism" stage- each mouth on the creature essentially has a small collider (set to IsTrigger) attached. When OnTriggerEnter occurs, the player checks if the colliding object has a "Status" script, and if it does, it'll check its own Status script's mass against the colliding object's Status script's mass, and if it's smaller (not just smaller, but like 20% smaller), proceed to damage it, or eat it if it's health is low enough (health can also be stored in the same script). There's an additional check to see if the "type" is appropriate, since certain mouths can only eat plant objects, certain mouths can only eat meat objects, and certain mouths can eat both.
All of this is fairly straightforward- just go to the Unity Learn site and watch the basic tutorials on MonoBehaviours / Components, Colliders, and Triggers. I would personally go though the entire "Interface and Essentials" section and the beginner section for "Scripting" before even opening up Unity (except to follow along). It only takes a couple of hours, and it will make your experience with Unity FAR less stressful.
Hope that helps!