M
M
MavShieldt2021-09-14 15:49:50
C++ / C#
MavShieldt, 2021-09-14 15:49:50

Why is the variable not being changed in the script?

There are two scripts: Route.cs and Point.cs.
Route.cs clings to prefabs with the trajectory of the game object, consisting of separate points, to which the Point.cs and BoxCollider2D scripts cling. Its task is to give another GameObject the coordinates of the point to which it is necessary to strive.
route.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Route : MonoBehaviour
{
    [SerializeField] private GameObject[] points;
    private int active_point = 0;
    private GameObject[] test;

    public Vector2 Target_cors()
    {
        if (!points[active_point].GetComponent<Point>().get_act())
        {
            print("Ehm?");
            if (active_point + 1 == points.Length)
            {
                return new Vector2(512, 251); // для объекта движения это будет означать его уничтожение
            }
            active_point++;
        }
        return points[active_point].transform.position;
    }
}


point.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Point : MonoBehaviour
{

    public bool active;

    private void Start()
    {
        active = true;
    }

    public void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Enemy"))
        {
            active = false;
        }
    }

    public bool get_act()
    {
        return active;
    }
}


The problem is this: Route.cs simply does not see the changes in Point.cs, attached to, in fact, the point. In the inspector (and even inside the Point.cs script, if you call print's on the active variable in Update() on Point, and even if you call it via get_act() inside Point.cs), you can easily see how the active variable becomes false when getting closer to her. But Route.cs continues to receive the active state from the point, no matter how you manipulate the code in Point.cs.
What is the reason for this and how can it be fixed? I sin on some work of arrays or how GetComponent works, but I'm not sure and I don't know how to fix it.

Thanks in advance for your help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Farawa, 2021-09-15
@Farawa

in your code it is written as if each enemy has its own Route and based on this I can offer the following implementation:

[SerializeField] private Queue<GameObject> points;

    public Vector2 GetTargetPosition()
    {
        if (points.Count == 0)
        {
            //destroy;
        }
        var point = points.Dequeue();
        return point.transform.position;
    }

it turns out the enemy needs to register:
if he reached the point, then request the next one.
not tested, but should work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question