Hi! I’m absolutely new to Unity. I’ve made few very simple games with Allegro 5 and I know some C++ (just a little!), but C# and Unity are new to me. So please explain everything carefully
I would be very greatful for both a solution and a thorough explanation.
First of all, I’ve been following this tutorial: Shooting (2/2) — Pixelnest Studio
I have a WeaponScript attached to both player and enemy prefabs. I want it to detect if my player/enemy has a “barrel tip”. If it has I want the shot bullet to spawn at the barrel tip. If it has no barrel tip I want the bullet to spawn where the player/enemy currently is.
A “barrel tip” would be a point (gameObject) being in a constant position relative to the player/enemy. So I guess it would have to be its child. But how to code the script? Remember that in the future the player/enemy might have other children and I don’t want it to break then.
Cheers!
An easy solution for this problem is to create a script to use as a marker. Say the script was called ‘BarrelTip’. The script does not have to contain anything…perhaps just an empty Start() function. If your character has a barrel tip, then you would add an empty game object at the tip position (or use a visible barrel tip object) and make that object a child of the player. Then you would attach this script. In the code you could do this:
Vector3 bulletPos;
BarrelTip bt = gameObject.GetComponent<BarrelTip>();
if (bt != null) {
bulletPos = bt.transorm.position;
}
else {
bulletPos = transform.position;
}
I’m assuming this code on the player (the one with the transform to use if the barrel tip is not found, and that the barrel tip is a child.
Another solution is to create a variable in your player script:
public Transform barrelTip;
Then you would initialize this variable only when there is a barrel tip object. If you are building a prefab, you can drag and drop the empty game (or visible) object that holds the barrel tip position on to this variable in the inspector. The code would be:
Vector3 bulletPos;
if (barrelTip != null) {
bulletPos = barrelTip.position;
}
else {
bulletPos = transform.position.
}
If the barrel tip object will always have the same parent/child relationship with the player or enemy object, another solution is to use Transform.Find() and specify a path to that object. For example, if the barrel tip is always a direct child of the player/enemy, you can do:
Vector3 bulletPos;
Transform tr = transform.Find("BarrelTip");
if (tr != null) {
bulletPos = tr.position;
}
else {
bulletPos = transform.position;
}
Assumes that the game object has the name ‘BarrelTip’.