- Home /
How do I get an object to inherit "something" from another game object that it has no parent/child relationship to?
So I have my gun and bullet. The bullet is not a child of the gun. My gun has a parent with a target. I need the bullet to have the same target without referencing the target itself.
The gun does this on a condition
Instantiate (attack, attackPosition.position, Quaternion.identity);
The bullet does this when instantiated
rb.MovePosition (rb.position + targetVector.normalized * Time.deltaTime * attackSpeed);
The targetVector is on the gun's parent.
There's a simple method by which to think of these things. Inheritance requires one to say that the subject "IS-A" thing. In this case, a bullet is not a gun, so inheritance would not seem to be the correct way of thinking. When the answer to "is it a...." is no, avoid inheritance. Ins$$anonymous$$d, when the answer to the question "does it have a..." is yes, this suggests containment, not inheritance. The gun will "have a" bullet, but the bullet will not "have a" gun, it will be owned by a gun. The relationship isn't a parent child, but a container and an element which it contains. This means PizzaPie's idea of having the gun class instantiate a bullet and contain it is on track. This "is-a" or "has-a" verbiage is from older computer science basics, and it's a classic.
Answer by PizzaPie · Jul 05, 2018 at 10:03 AM
You could pass directly the targetVector after the Instatiation (inside the Gun Script) ex.
//Gun class
GameObject bullet = Instantiate (attack, attackPosition.position, Quaternion.identity);
bullet.GetComponent<Bullet>().Init(targetVector);
//Bullet class
private bool isSet = false;
private Vector3 targetVector;
public void Init(Vector3 targetVector){
this.targetVector = targetVector;
isSet = true;
}
void FixedUpdate(){
if(!isSet)
return;
rb.MovePosition(); // as you have it
}
It would be better if it could be passed via the Constructor but Unity won't allow custom constructors on MonoBehaviours. Fixed Cheers
What do you mean by the last part? $$anonymous$$y rb.$$anonymous$$ovePosition is usually in FixedUpdate anyway.
That was a terrible answer fixed it. Not sure if FixedUpdate is called between the Instatiate and the GetComponent thus the use of the isSet flag, if it isn't (called) it is useless. Also it can be done with a propery ins$$anonymous$$d of a function.
Your answer
![](https://koobas.hobune.stream/wayback/20220612170055im_/https://answers.unity.com/themes/thub/images/avi.jpg)