FindGameObject/sWithTag

Hi guys.
Simply put, I need to do a certain operation with all objects that have a certain tag(“House1floors”).
I didn’t post the whole script, because it’s long and does not play any role. I just do not understand one detail at the beginning.

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

public class floorshide : MonoBehaviour
{
    public GameObject Roof;
   
    void Start()
    {
    }
   
    void Update()
    {
        Roof = GameObject.FindGameObjectWithTag("House1floors");
    }
   
    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
            SetMaterialTransparent();
            iTween.FadeTo(Roof, 0, 0);
        }
    }
   
     private void SetMaterialTransparent()
    {
...

So one of the objects becomes transparent (this is exactly what I want). But I need many objects to become transparent, not just one. Although I made this tag for a dozen objects, the script only performs an action on one. That is the problem. Then I tried doing something like: Roof = GameObject.FindGameObjectsWithTag(“House1floors”)[0]; and then of course this script works for the object whose number is indicated in brackets. I’ve tried manually writing like this: [0, 1, 2] but that doesn’t work either. So how do I make it so that the operation is performed for all objects with this tag?

You need to find them all. Once you find them all, loop through them doing the thing you want to each one. Look up a short ForLoop tutorial on youtube. See if you can’t figure it out

FindGameObjectsWithTag.
Plural.
Unity - Scripting API: GameObject.FindGameObjectsWithTag

var foundObjs = ....FindGameObjectsWithTag("....");
foreach(var curObject in foundObjs){
     setMaterialTransparent(curObject);
}

Sorry, i don’t know why you are writing VAR, this is not in the manual on the link. And besides, I do not understand how and where exactly I should insert this code. I tried the following and it gave me an error:

public class floorshide : MonoBehaviour
{
    public GameObject[] Roof;
 
    void Start()
    {
    }
 
    void Update()
    {
        if (Roof == null)
            Roof = GameObject.FindGameObjectsWithTag("House1floors");
        foreach (GameObject House1floors in Roof){}
    }
 
    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
            Debug.Log("2 Floor");
            SetMaterialTransparent();
            iTween.FadeTo(Roof, 0, 0);
        }
    }
 
     void SetMaterialTransparent()
    {
...

argument 1 cannot convert from ‘unityengine.gameobject[ ]’ to ‘unityengine.gameobject’
(String number 22)

UPD

If I change all GameObjects to GameObject, then I get the following error:
foreach statement cannot operate on variables of type ‘GameObject’ because ‘GameObject’ does not contain a public instance definition for ‘GetEnumerator’
It looks like Unity doesn’t want to work with GameObjects

From this tutorial about loops:
https://answers.unity.com/questions/423622/for-loop-c.html

   ...
     void OnTriggerEnter(Collider other)
    {
        for (int i = 0; i < 50; i++){
        if (other.tag == "Player")
        {
            Debug.Log("2 Floor");
            SetMaterialTransparent();
            iTween.FadeTo(0, 0);
        }
        }
    }
...

Argument 1: cannot convert from ‘int’ to ‘UnityEngine.GameObject’
(string 9)

Could you not do something like this?

public class floorshide : MonoBehaviour
{
    public GameObject[] Roof;

    void Update()
    {
        Roof = GameObject.FindGameObjectsWithTag("House1floors");
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
            foreach(GameObject go in Roof)
            {
                //Set the material for each of the roof game objects transparent
                go.GetComponent<MeshRenderer>().material.color.a = 0;
            }
        }
    }
}

Also consider whether you really want to set the Roof variable once every frame.

Than i have this error:
Cannot modify the return value of ‘Material.color’ because it is not a variable


Ok, maybe it will be better to post all script here:

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



public class RoofHouse : MonoBehaviour
{
    public GameObject Roof = null;

    void OnTriggerEnter(Collider other)
    {
        //if(IsCharacter(collider))
        if (other.tag == "Player")   
        {
            Debug.Log("1 Floor");
            SetMaterialTransparent();
            iTween.FadeTo(Roof, 0, 1);
        }
    }

    private bool IsCharacter(Collider collider)
    {
      // Implement you logic here if it is your player that is the collider
      return true;
    }

    private void SetMaterialTransparent()
    {
        foreach (Material m in Roof.GetComponent<Renderer>().materials)
        {
            m.SetFloat("_Mode", 2);
            m.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
            m.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
            m.SetInt("_ZWrite", 0);
            m.DisableKeyword("_ALPHATEST_ON");
            m.EnableKeyword("_ALPHABLEND_ON");
            m.DisableKeyword("_ALPHAPREMULTIPLY_ON");
            m.renderQueue = 3000;
        }
    }

    private void SetMaterialOpaque()
    {
        foreach (Material m in Roof.GetComponent<Renderer>().materials)
        {
            m.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
            m.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
            m.SetInt("_ZWrite", 1);
            m.DisableKeyword("_ALPHATEST_ON");
            m.DisableKeyword("_ALPHABLEND_ON");
            m.DisableKeyword("_ALPHAPREMULTIPLY_ON");
            m.renderQueue = -1;
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.tag == "Player")
        {
            // Set material to opaque

            iTween.FadeTo(Roof, 1, 1);
            Invoke("SetMaterialOpaque", 1.0f);
        }
    }
}

I took it from here:
https://www.patreon.com/posts/c-script-to-hide-7678022

Then a line appears in the unit into which I have to drag the object, which will then become transparent. However, I would not like to add a script and an object every time, but simply make it work for every object that has a specific tag. And I did what in the very first post. This works, but only for some reason for one object, and not all objects with this tag.

7750422--975099--Scrjjjjjjeenshot_1.jpg

Hi I have just a curious problem: I don’t know why but when I run:
gemsY=GameObject.FindGameObjectsWithTag(“gemY”)
Debug.Log("|||||| There are in to gemY: "+gemsY.Length);

it prints length is = 0, but there are a couple of objects having that Tag…any idea about the mistake?

Please don’t necro-post. If you have an issue, start a fresh post. It’s FREE!

How to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, log output, variable values, and especially any errors you see
    - links to documentation you used to cross-check your work (CRITICAL!!!)

The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven’t put effort into finding the documentation, why should we bother putting effort into replying?

If you have no idea what is happening then it is…

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://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

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://discussions.unity.com/t/839300/3

“When in doubt, print it out!™” - Kurt Dekker (and many others)

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