Adding variable to object
I have the following situation:
I use Unity Playground to create some sort of Asteroids for practicing my unity skills, which realy suck a lot.
I followed the "How to Start Making Games - Unity Playground (Beginner Friendly)" instructions so far and replicated the identical concept. There is a script called "DestroyForPointsAttribute.cs"
I edited it like follows. (more on that below) using UnityEngine; using System.Collections;
[AddComponentMenu("Playground/Attributes/Destroy For Points")]
public class DestroyForPointsAttribute : MonoBehaviour
{
public int pointsWorth = 5;
private UIScript userInterface;
private int this.gameObject.healthPoints = 15;
private void Start()
{
// Find the UI in the scene and store a reference for later use
userInterface = GameObject.FindObjectOfType<UIScript>();
}
//This will create a dialog window asking for which dialog to add
private void Reset()
{
Utils.Collider2DDialogWindow(this.gameObject, false);
}
//duplication of the following function to accomodate both trigger and non-trigger Colliders
private void OnCollisionEnter2D(Collision2D collisionData)
{
OnTriggerEnter2D(collisionData.collider);
}
// This function gets called everytime this object collides with another trigger
private void OnTriggerEnter2D(Collider2D collisionData)
{
// is the other object a Bullet?
if(collisionData.gameObject.CompareTag("Bullet"))
{
if(this.gameObject.healthPoints == null)
{
this.gameObject.healthPoints = 15;
}
this.gameObject.healthPoints -= 5;
if (this.gameObject.healthPoints < 1)
{
if(userInterface != null)
{
// add one point
BulletAttribute b = collisionData.gameObject.GetComponent<BulletAttribute>();
if(b != null)
{
userInterface.AddPoints(b.playerId, pointsWorth);
}
else
{
Debug.Log("Use a BulletAttribute on one of the objects involved in the collision if you want one of the players to receive points for destroying the target.");
}
}
else
{
Debug.Log("There is no UI in the scene, hence points can't be displayed.");
}
// then destroy this object
Destroy(gameObject);
}
}
}
}
I tried: private int this.gameObject.healthPoints = 15; private int gameObject.healthPoints = 15; public >the rest = the same<
As you already can see, I cannot wrap arount my head around the structure of this stuff. C# is killing me. This script is directly linked to the asteroid.
Usually the script will just destroy asteroid and the bullet stays and it gives the player 1 point or what ever was configured.
I want the object to have health, but somehow I cannot set the variable to the object (asteroid).
I do not realy get it. Why can I not just use those variables?
@HeartOfGermany Note you can just write healthPoints
ins$$anonymous$$d of this.gameObject.healthPoints
. Now what specifically goes wrong? Try to limit your code to the smallest possible issue-reproducing example, and edit your question to quote just that, it might help us understand your issue.
Answer by streeetwalker · Mar 08, 2020 at 04:29 PM
Hey I just saw this. Sorry for that no one has replied sooner.
I want to understand your problem, so where is the issue: You are trying to set the health point on the gameobject this script is attached to?
If that is the case, I'm not sure why you are using:
private int this.gameObject.healthPoints = 15;
Instead, it should be:
private int healthPoints = 15;
// likewise elsewhere in the script,
// you just reference healthPoints
if ( healthPoints < 1)
You do not need the 'this.gameObject' because you want to set the health points in the script, not on the game object the script is a component of. The game object "owns" the script when you attach it. You should not want/need/ or even try to add a property to the gameobject itself.
That explaination really helped a lot, thank you!
So far understood. What, if I want to call the health variable from another script?
With gsc I could for example create an array like:
level.asteroid[1] ... level.asteroid[9999]
So I could use something like:
level.asteroid[123].health and done! I know, GSC is a really simple scripting language. But I do not fully grasp, how to archive something like that. You know what, I will test around some the next time. :)
@HeartOfGermany
> level.asteroid[123].health
That will only work if those are script objects on your game objects.
Often we store gameobject references in an array.
To get at at health in the script attached to a game object then, you could do:
// replace ScriptName with the script component class name
level.asteroid[123].GetComponent<ScriptName>().health
but that is costly in terms of processor time if you have to do it a lot. There are several approaches to make it easier. One way create an array of scripts ins$$anonymous$$d of game objects, and use the script to get at the game object.
Of course you have to declare the array or list data type as ScritpClassName[] -- what ever the class name is. So, Asteroid[] if the name of the class is 'Asteroid'
Say, you instance a prefab that already has the script on it - you should be doing that. Assu$$anonymous$$g the script class is 'Asteroid' in pseudo code:
// in your prefab creation loop using index i
GameObject g = (GameObject) Instantiate ( ..... );
level.asteroid[i] = g.GetComponent<Asteroid>();
// now you can state
level.asteroid[i].gameObject.transform.position
level.asteroid[i].health
Another way to do it is to create a list of objects: Create a class that contains a game object and it's script as variables, in a separate script file:
public class AsteroidObj {
public Gameobject go;
public Asteroid sc;
// this is the object constructor:
public AsteroidObj( GameObject _go, Asteroid _sc ){
this.go = _go;
this.as = _sc;
}
} // do not attach this AsteroidObj.cs script to any game object!
// then in any other script file:
private AsteroidObj[] asteroidList = new AsteroidObj[200];
// really better to use a list than an array, but just for example
// then in your asteroid creation loop
GameObject g = (GameObject) Instantiate ( ..... );
Asteroid sc = g.GetComponent<Asteroid>();
asteroidList[i] = new AsteroidObj( g, sc );
// then to access the member fields of the object:
asteroidList[i].sc.health = 100f;
asteroidList[i].go.transform.position.y = 5f;
There are many ways to approach it.
@HeartOfGermany, here is a more comprehensive example
public class AsteroidObj {
// sometimes handy to keep references to
// the gameObject name and it's list index
public string id; // my gameObject name
public Transform tr; // of my gameObject
public Asteroid sc; // script of my gameObject;
public int index; // my position in a list
// the object constructor:
public AsteroidObj( string _id, Transform _tr, Asteroid _sc, int _idx ){
this.id = _id;
this.tr = _tr;
this.as = _sc;
this.index = _idx;
}
} // do not attach this AsteroidObj.cs script to any game object!
// then in any other script file:
private List<AsteroidObj> asteroidList = new List<AsteroidObj>;
// really better to use a list than an array
// then in your asteroid creation loop
GameObject g = (GameObject) Instantiate ( ..... );
g.name = "asteroid_" + i; // unique name for each gameOject
Asteroid sc = g.GetComponent<Asteroid>();
AsteroidObj ao = new AsteroidObj( g.name, g.transform, sc, i ) ;
// good idea to keep a reference to the object in the script
// for example, collisions
// so in Asteroid class you declare public AsteroidObj astObj;
sc.astObj = ao;
asteroidList.Insert( i, ao );
// then to access the member fields of the object:
asteroidList[i].sc.health = 100f;
asteroidList[i].tr.position.y = 5f;
// and in a collision in any script
void OnCollisonEnter( Collision collision ){
GameObject g = collision.gameObject;
Asteroid as = g.GetComponent<Asteroid>();
AsteroidObj asObj = as.astObj;
Debug.log( "collided: " + asObj.id + ", list index: " + asObj.index);
Destroy( g );
// assumes this script has a reference to the asteroidList
asteroidList.RemoveAt( asObj.index );
Destroy( asObj ); // destroy the AsteroidObj object
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612223838im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to make GUI variables compatible with the UI system? 0 Answers
How to sum up values from clones 1 Answer
Health variable not changing 1 Answer
My health bars image.fillAmount doesnt change. 4 Answers
Health pickup script issue -1 Answers