- Home /
Method returning null, when referenced from another script
Hi, so in my 'Movement' script I have a method SetTarget(), that returns a string.
public string SetTarget()
{
enemyTitles = new string[5] { "Hoplite", "Archer", "Cavalry", "Peltast", "Slinger"};
if (target == null)
Debug.Log("Obviously something has gone wrong, target is null!");
if (Input.GetMouseButtonDown(1))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
foreach (string enemy in enemyTitles)
{
if (Physics.Raycast(ray, out hit) && target != null)
{
target.transform.position = hit.point;
if (hit.transform.gameObject.tag == enemy)
{
enemySelected = true;
Debug.Log("engaging now." + enemy);
return enemy;
}
else { enemySelected = false; }
}
}
}
return null;
}
Now, this is returned successfully: Debug.Log("engaging now." + enemy); Giving the correct and expected result. However, in my other script:
private float Attack()
{
float finalAttackDamage = default(float);
//I want different enemies to be dealt damage in accordance with their type.
if (move.SetTarget() == "Hoplite")
{
hoplite = GetComponent<Hoplite>();
finalAttackDamage = hoplite.baseDamage;
Debug.Log(finalAttackDamage);
}
if (move.SetTarget() == "Archer")
{
hoplite = GetComponent<Hoplite>();
finalAttackDamage = hoplite.baseDamage + hoplite.counterArcher;
return finalAttackDamage;
}
if (move.SetTarget() == "Peltast")
{
hoplite = GetComponent<Hoplite>();
finalAttackDamage = hoplite.baseDamage + hoplite.counterPeltast;
return finalAttackDamage;
}
if (move.SetTarget() == "Slinger")
{
hoplite = GetComponent<Hoplite>();
finalAttackDamage = hoplite.baseDamage + hoplite.counterSlinger;
return finalAttackDamage;
}
if (move.SetTarget() == "Cavalry")
{
hoplite = GetComponent<Hoplite>();
finalAttackDamage = hoplite.baseDamage;
return finalAttackDamage;
}
return 0.0f;
}
move.SetTarget() is null. (I tested this earlier.) And I'm not sure why. I think I've referenced the script correctly:
public Movement move;
Below the class. And the reference is filled within the inspector.
For whatever reason SetTarget = one thing in the Movement script, and null in my other script, when I try and reference it.
I'm also aware I write code very inefficiently, I'll make improvements once I get the script working.
Your answer
![](https://koobas.hobune.stream/wayback/20220612112817im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# Turn Off / Null A Method 1 Answer
Variables are assigned but it returns null 2 Answers
Stop calling a function 1 Answer