0

i am having trouble updating my vector2 data from my function. The objective of this vector2 is to save the dead enemy position but when i use it globally it goes to 0,0 when inside the function it has the right values.

Heres is the code

 private Vector2 enemyPosition;

void Update()
{
    Debug.Log("enemyPosition update: " + enemyPosition);
    gameObject.transform.position = Vector2.MoveTowards(transform.position, enemyPosition, blobSpeed * Time.deltaTime);
}

public void createBlobMelee(GameObject enemy)
{
    enemyPosition = new Vector2(enemy.transform.position.x, enemy.transform.position.y);
    Debug.Log("enemyPosition: " + enemyPosition);
    randomBlobx = Random.Range(-1, 1);
    randomBloby = Random.Range(-1, 1);
    Vector2 randomBlobCreate = new Vector2(enemy.transform.position.x + randomBlobx, enemy.transform.position.y + randomBloby);
    Instantiate(gameObject, randomBlobCreate, Quaternion.identity);
}

And this is the results from the debug console.

Debug console

Thank you for you time, André Sousa

2 Answers 2

2

Try making your object as

public static Vector2 enemyPosition;

If it can not be static try public or try just static.

I have this problem very often, you just need to play with the public and static and see what works for you.

Sign up to request clarification or add additional context in comments.

4 Comments

although this is working now, it would be good to note as soon as you have more than one blob it won't work anymore and both bobs will share their position
I've never had this but it would be really good to know what causes this. I high advise you not fix this by making it static though. Enemy is something that there is very likely to be many of and static should only be used when you know that you only want one version of that variable in all places.
Access level should have no bearing on how it's accessed from within the same class/object. Something interesting must be happening because that's just not how C# works.
He did not show where he calls the createBlobMelee function from
1

The main problem is the public and private setting.

For more information look here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.