Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Script finding an object that should of been destroyed and replaced.

Discussion in 'Scripting' started by Fatmanboozer, Sep 19, 2023.

  1. Fatmanboozer

    Fatmanboozer

    Joined:
    May 8, 2022
    Posts:
    3
    Hello, first time posting and complete amateur, I've managed to bumble my way this far but pretty stuck now.

    I have a function that is calling 2 additional functions (tried as coroutines), one to replace some portal nodes and another to update the neighbours for pathfinding.

    At first I thought the problem was that it needs to run over multiple frames as the node is being destroyed and replaced but even after putting them into coroutines its still referencing the old portal which should be removed and destroyed.

    Extract from my Public void BuildMe function
    Code (CSharp):
    1.         if (!preview)
    2.         {
    3.             StartCoroutine(MapGen2.UpdatePortal(nList));
    4.             StartCoroutine(MapGen2.SetNeighbours());
    5.             sec.valid = false;
    6.            
    7.         }
    Update portals
    Code (CSharp):
    1.     public static IEnumerator UpdatePortal(List<GameObject> nList)
    2.     {
    3.         foreach (GameObject n in nList)
    4.         {
    5.             pathTiles.Add(n);
    6.         }
    7.         //loop through list to set nieghbours
    8.         foreach (GameObject p in portalList)
    9.         {
    10.             float x = p.transform.position.x;
    11.             float y = p.transform.position.y;
    12.             //check if portal is surrounded if so remove it and replace with path
    13.             if (GameObject.Find("BuiltNodes" + $"Node {x - 1} {y}") != null
    14.                 && GameObject.Find("BuiltNodes" + $"Node {x} {y - 1}") != null
    15.                 && GameObject.Find("BuiltNodes" + $"Node {x + 1} {y}") != null
    16.                 && GameObject.Find("BuiltNodes" + $"Node {x} {y + 1}") != null)
    17.             {
    18.                 if (pathTiles.Contains(p))
    19.                 {
    20.                     pathTiles.Remove(p);
    21.                 }
    22.                 Node pNode = p.GetComponent<Node>();
    23.                 Node nleft = GameObject.Find("BuiltNodes" + $"Node {x - 1} {y}").GetComponent<Node>();
    24.                 Node ndown = GameObject.Find("BuiltNodes" + $"Node {x} {y - 1}").GetComponent<Node>();
    25.                 Node nright = GameObject.Find("BuiltNodes" + $"Node {x + 1} {y}").GetComponent<Node>();
    26.                 Node nup = GameObject.Find("BuiltNodes" + $"Node {x} {y + 1}").GetComponent<Node>();
    27.  
    28.  
    29.  
    30.                 if (nleft.Neighbours.Contains(pNode))
    31.                 {
    32.                     nleft.Neighbours = new List<Node>();
    33.                 }
    34.                 if (ndown.Neighbours.Contains(pNode))
    35.                 {
    36.                     ndown.Neighbours = new List<Node>();
    37.                 }
    38.                 if (nright.Neighbours.Contains(pNode))
    39.                 {
    40.                     nright.Neighbours = new List<Node>();
    41.                 }
    42.                 if (nup.Neighbours.Contains(pNode))
    43.                 {
    44.                     nup.Neighbours = new List<Node>();
    45.                 }
    46.                 GameObject replacePath = Instantiate(path);
    47.                 Destroy(p);
    48.                 portalList.Remove(p);
    49.                 replacePath.transform.position = new Vector3Int((int)x, (int)y, 0);
    50.                 replacePath.name = $"Node {replacePath.transform.position.x} {replacePath.transform.position.y}";
    51.                 replacePath.tag = "Path";
    52.                 replacePath.GetComponent<Node>().SetCoords(new NodeCoords { Pos = new Vector3(replacePath.transform.position.x, replacePath.transform.position.y) });
    53.                 replacePath.transform.parent = GameObject.Find("BuiltNodes").transform;
    54.                 pathTiles.Add(replacePath);
    55.             }
    56.             else if (!pathTiles.Contains(p))
    57.             {
    58.                 pathTiles.Add(p);
    59.             }
    60.         }
    61.        
    62.         yield return null;
    63.     }
    set neighbours
    Code (CSharp):
    1.     public static IEnumerator SetNeighbour()
    2.     {
    3.         if (!pathTiles.Contains(GameManager.Target))
    4.         {
    5.             pathTiles.Add(GameManager.Target);
    6.         }
    7.         foreach (GameObject n in pathTiles)
    8.         {
    9.             Node curNode = n.GetComponent<Node>();
    10.             float x = curNode.transform.position.x;
    11.             float y = curNode.transform.position.y;
    12.             if (GameObject.Find("BuiltNodes" + $"Node {x - 1} {y}") != null)
    13.             {
    14.                 Node foundNode = GameObject.Find("BuiltNodes" + $"Node {x - 1} {y}").GetComponent<Node>();
    15.                 string tag = foundNode.tag;
    16.                 if (tag != "Node" && tag != null)
    17.                 {
    18.                     if (!curNode.Neighbours.Contains(foundNode))
    19.                     {
    20.                         curNode.Neighbours.Add(foundNode);
    21.                     }
    22.                 }
    23.             }
    24.             if (GameObject.Find("BuiltNodes" + $"Node {x} {y - 1}") != null)
    25.             {
    26.                 Node foundNode = GameObject.Find("BuiltNodes" + $"Node {x} {y - 1}").GetComponent<Node>();
    27.                 string tag = foundNode.tag;
    28.                 if (tag != "Node" && tag != null)
    29.                 {
    30.                     if (!curNode.Neighbours.Contains(foundNode))
    31.                     {
    32.                         curNode.Neighbours.Add(foundNode);
    33.                     }
    34.                 }
    35.             }
    36.             if (GameObject.Find("BuiltNodes" + $"Node {x + 1} {y}") != null)
    37.             {
    38.                 Node foundNode = GameObject.Find("BuiltNodes" + $"Node {x + 1} {y}").GetComponent<Node>();
    39.                 string tag = foundNode.tag;
    40.                 if (tag != "Node" && tag != null)
    41.                 {
    42.                     if (!curNode.Neighbours.Contains(foundNode))
    43.                     {
    44.                         curNode.Neighbours.Add(foundNode);
    45.                     }
    46.                 }
    47.             }
    48.             if (GameObject.Find("BuiltNodes" + $"Node {x} {y + 1}") != null)
    49.             {
    50.                 Node foundNode = GameObject.Find("BuiltNodes" + $"Node {x} {y + 1}").GetComponent<Node>();
    51.                 string tag = foundNode.tag;
    52.                 if (tag != "Node" && tag != null)
    53.                 {
    54.                     if (!curNode.Neighbours.Contains(foundNode))
    55.                     {
    56.                         curNode.Neighbours.Add(foundNode);
    57.                     }
    58.                 }
    59.             }
    60.         }
    61.  
    62.         if (GameManager.Instance.State == GameState.MapGen)
    63.         {
    64.             GameManager.Instance.UpdatePlayerSate(PlayerState.Mapping);
    65.             GameManager.Instance.UpdateGameSate(GameState.Wave);
    66.         }
    67.         yield return null;
    68.     }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Well... first of all this approach...

    Is really just pure craziness, imnsho.

    Remember the first rule of GameObject.Find():

    Do not use GameObject.Find();

    More information: https://starmanta.gitbooks.io/unitytipsredux/content/first-question.html

    More information: https://forum.unity.com/threads/why-cant-i-find-the-other-objects.1360192/#post-8581066

    In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.

    If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way(tm) success of accessing things in your game.




    For your above use, put the relevant objects (perhaps the Node to be more efficient than storing the GameObject and digging into it each time?) into some kind of collection, perhaps indexed by the X/Y values in question.




    Otherwise... it sounds like you have some kind of bug, and gazing at code is rarely helpful in that case.

    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    If your problem is with OnCollision-type functions, print the name of what is passed in!

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
     
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    This is way, way to many
    GameObject.Find
    calls... You definitely don't want to be maintaining this kind of data structure via their game object names.

    You need an actual data structure to represent, or maintain references to these nodes. Can be as simple as an array that references all these nodes. Then it's simple math to find surrounding nodes, etc.

    Worth also remember that Object.Destroy doesn't actually do so until the end of frame. Your co-routine in the second segment of code isn't yielding until you've done everything, so there's no change for the object to have been properly cleaned up. You should be yielding in the loop.
     
  4. Fatmanboozer

    Fatmanboozer

    Joined:
    May 8, 2022
    Posts:
    3
    @Kurt-Dekker @spiney199 Thanks and sorry for my awful code.
    I will try and rebuild this but how do i go about making a collection of gameobjects that i can reference/index using their vectors?

    I am generating these nodes during the game as the player will build the map as they play so i need to add them to (im guessing) a list still, but I need to be able to find the object in the list based on vector2.

    Im also checking to see if a portal is surrounded by nodes, there will be times when its not so how do i avoid erroring when it cant locate the the object in the array?
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    You can see a full example that spawns GameObjects in a grid and tracks them by x/y here:

    https://github.com/kurtdekker/makeg...ocGenStuff/SpawningInAGrid/SpawningInAGrid.cs

    MakeGeo is presently hosted at these locations:

    https://bitbucket.org/kurtdekker/makegeo

    https://github.com/kurtdekker/makegeo

    https://gitlab.com/kurtdekker/makegeo

    https://sourceforge.net/p/makegeo
     
  6. Fatmanboozer

    Fatmanboozer

    Joined:
    May 8, 2022
    Posts:
    3
    Thanks, my map wont be square due to the nature of the game but I found what i needed in the end. Dictionary<Vector2, Node>