How to access a local variable declared in foreach

public List list;
public GameObject rootObj;

        foreach(Transform child in list)
        {
			GameObject assetRoot = rootObj;
			string assetPath = AssetDatabase.GetAssetPath(assetRoot);
			GameObject contentsRoot = PrefabUtility.LoadPrefabContents(assetPath);
			contentsRoot.child.gameObject.SetActive(true); //it's doesn't work

			PrefabUtility.SaveAsPrefabAsset(contentsRoot, assetPath);
			PrefabUtility.UnloadPrefabContents(contentsRoot);
        }

How do I turn off the local variable “child” while using Load Prefab Contents? Where it says “//it’s doesn’t work” is an example of what I’m trying to do. I need to turn off the game object in the “child” variable in the prefab. But I can’t do it with LoadPrefab Contents. Is there a way to do this?

Hi @SuperStarGaming235 I’m not entirely sure what you’re trying to accomplish here, other than perhaps disabling or enabling a child object of a prefab.

The line “GameObject assetRoot = rootObj;” is not needed. assetRoot doesn’t change or update within the loop to anything other than the rootObj. Therefore, the GetAssetPath call can just simply use rootObj directly.

What is the difference between the rootObj object and the return from LoadPrefabContents? The load seems superfluous to me based on this code snippet, as it should just be the same thing as rootObj.

From where is list filled? This code sample doesn’t show any evidence of it containing anything, let alone anything related to contentsRoot / rootObj. The only thing I can think is it’s assigned by drag/drop in the editor inspector.

Since the foreach loop is using the contents of list, the child variable has nothing to do with contentsRoot. Even if child is a child of contentsRoot, simply say “child.gameObject.SetActive(true);”. Though, how list is related to the contentsRoot object, this is unclear. Perhaps if you updated the question with more information about what you’re actually trying to accomplish, we can assist you in solving that, rather than an error in code which doesn’t make much sense (to me).

Hi, @AnOrdinarySandwich , using root Obj, I get the path to the prefab, and using contents Root, I edit it. If I just write child.GameObject.SetActive(true), then the child objects from the list “list” will be turned off, but in the prefab this function is triggered via LoadPrefabContents. “list” stores child objects that I got from another script. But I need to turn off these child objects from the prefab, because if I just write “child.GameObject.SetActive(true)”, then this will work only with a regular object on the stage or a prefab on the stage, but not on the prefab itself, which lies in the project folder. The question is: how do I turn off all objects from the list in the prefab, which is located in the project folder, and not on the stage?