Hello
I tried asking this question in UnityAnswers and struggled to get a response, so I thought I would try it here. I found a tremendous amount of useful answers in Unity Answers, but at times it seems if someone attempts to answer your question and its quite not what you expected, no one else will make another attempt. The unanswered questions seem to attract the most attention.
Anyways, I have a script placed on my weapon items that adds a script based on the tag of a parent two levels up in the hierarchy, which would be a weaponmount on a character. And it works fine for that purpose. However, if I just want to throw the weapon in the scene my variable wpnChk will return a null because there is no second level parent as you can see in the following c# code:
using UnityEngine;
using System.Collections;
public class WeaponInit : MonoBehaviour {
private string wpnCheck;
void Start () {
wpnCheck = transform.parent.parent.tag;
if (wpnCheck == "Enemy")
gameObject.AddComponent ("EnemyWeaponScript");
if (wpnCheck == "Ally")
gameObject.AddComponent ("AllyWeaponScript");
if (wpnCheck == "Player")
gameObject.AddComponent ("WeaponScript");
Debug.LogWarning(wpnCheck);
}
}
So, in a attempt to fix that I removed declaring the wpnCheck variable and tried an if else statement in its place:
if (wpnCheck != null)
wpnCheck = transform.parent.parent.tag;
else
wpnCheck = transform.parent.tag;
Now it only returns the else statement even if the weapon mounts on a character. What I am trying to do with this script is look at the tag of the second level parent and then add the appropriate script or no script if it is null. This might not even be possible with the approach I am trying.
Does anyone have a better approach or can point me in the right direction of what I am doing wrong?
Thanks for reading.