- Home /
The question is answered, right answer was accepted
[SOLVED]Get variable of an object that creates different object with a script
Hey guys again,
I am really sorry to ask maybe stupid question but I am struggling with this for a long time. I've searched through forums and answers but cant find my exact problem.
I have got a tower(gameObject) with a script where I can drag and drop bullet prefab with a bullet script.
How can I get a reference to a variable from Tower.script to Bullet.script ? Tower.script instantiates bullets which fly to target and I want to tell every bullet what dmg it should take to the enemy.
Keep in mind that I want to create many towers and every tower is upgradeable so dmg will change based on every upgrade of the tower.
Static variable is not an option and GetComponent works if script are on the same gameobject or child object (bullets are independent gameobjects). FindObject method is slow and wont work coz of many levels of towers. The only moment they have something in common is when bullet gameobject with a script is dropped in tower.script .
Maybe I am missing something or is there different use from these options?
Tower.script
// shoot next bullet?
timeLeft -= Time.deltaTime;
if (timeLeft <= 0.0f) {
// find the closest target (if any)
Unit target = findClosestTarget();
if (target != null) {
// is it close enough?
if (Vector3.Distance(transform.position, target.transform.position) <= range) {
// spawn bullet
GameObject g = (GameObject)Instantiate(bulletPrefab.gameObject, transform.position, Quaternion.identity);
// get access to bullet component
Bullet b = g.GetComponent<Bullet>();
// set destination
b.setDestination(target.transform);
// reset time
timeLeft = fireRate;
}
}
}
Bullet.script
// was target reached?
if (transform.position.Equals(destination.position)) {
Unit t = destination.GetComponent<Unit>();
if (t != null)
{
t.health = t.health - 1 (tower.dmg should be here);
// unit elimination
if (t.health <= 0)
t.onDeath();
}
// destroy bullet
Destroy(gameObject);
}
Answer by Kiwasi · Jun 23, 2014 at 03:32 AM
I don't understand the question.
You already have a good reference to the bullet component at line 12. At line 13 you could write
b.damage = dmg;
Then on your bullet script use
public int damage;
// Skip to line 9
t.health = t.health - damage;
Lol I have to admit this was really stupid question. I was writing this at about one clock A$$anonymous$$ so I wasn't thinking properly. Thanks anyway, my bad, next time I will check more my code than forums and answers on unity3d. Really appreciated :) Once game is done I will all people who helped me list in credits :)
Follow this Question
Related Questions
How to run function in another script with prefabs? C# 2 Answers
the most RESOURCE EFFICIENT way of referencing 1 Answer
how can i make a player get in a vehicle? 1 Answer
audio between scripts 1 Answer
Turret A.I scripts 1 Answer