How can I destroy all the shaders in the world? - c#

This script check if specific GameObjects exist then destroy them and add new same GameObjects.
If not exist it will add a new once anyway. The idea is to destroy anyway if exist and then add new o make it clean and not messed.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ObjectsReplace : MonoBehaviour
{
public GameObject prefabToInit;
public bool deleteAllShaders = false;
private const string c_doorRight = "Door_Right";
private const string c_doorLeft = "Door_Left";
private const string c_doorShieldFxLocked = "DoorShieldFXLocked";
public List<GameObject> FindDoors(string[] SpecificParents, bool AllParents)
{
GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);
List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();
if (AllParents == false)
{
List<GameObject> toRemove = new List<GameObject>();
for (int i = 0; i < allDoors.Count; i++)
{
bool match = true;
for (int x = 0; x < SpecificParents.Length; x++)
{
match &= allDoors[i].transform.parent.name != SpecificParents[x];
}
if (match)
{
toRemove.Add(allDoors[i]);
}
}
foreach (var it in toRemove)
{
allDoors.Remove(it);
}
}
return allDoors;
}
public void DeleteAllShaders()
{
if(deleteAllShaders == true)
{
FindDoors(null, true);
}
}
public void UpdateOrAddShaderPrefabToDoors()
{
var allDoors = FindDoors(new string[]{ "Wall_Door_Long_01", "Wall_Door_Long_02" }, false);
HashSet<GameObject> prefabParentsOfDoorsNeedRemove = new HashSet<GameObject>();
allDoors.ForEach(doorGameObject =>
{
List<GameObject> shadersChildren = new List<GameObject>();
for (int i=0; i<doorGameObject.transform.childCount ;i++)
{
if (doorGameObject.transform.GetChild(i).name.StartsWith(c_doorShieldFxLocked))
{
shadersChildren.Add(doorGameObject.transform.GetChild(i).gameObject);
}
}
foreach (GameObject shader in shadersChildren)
{
GameObject outermostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(shader);
prefabParentsOfDoorsNeedRemove.Add(outermostPrefabInstanceRoot);
}
});
foreach (GameObject parent in prefabParentsOfDoorsNeedRemove)
{
Modify(parent, RemoveFunc);
}
HashSet<GameObject> prefabParentsOfDoors = new HashSet<GameObject>();
allDoors.ForEach(doorGameObject =>
{
GameObject outermostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(doorGameObject);
prefabParentsOfDoors.Add(outermostPrefabInstanceRoot);
});
foreach (GameObject parent in prefabParentsOfDoors)
{
AddShaderToPrefab(parent);
}
}
private void AddShaderToPrefab(GameObject child)
{
Modify(child, AddShaderToAllDoorsFunc);
}
private GameObject AddShaderToAllDoorsFunc(GameObject prefab)
{
var children = prefab.GetComponentsInChildren<Transform>();
//Debug.Log($"Total child count before:{children.Count()}");
int doorsFound = 0;
foreach (Transform trans in children)
{
if (trans.name == c_doorLeft || (trans.name == c_doorRight))
{
//Debug.Log("Found door, adding");
GameObject shader = GetDoorShaderPrefab();
// clone prefab and attach to parent
Instantiate(shader, trans);
doorsFound++;
}
}
children = prefab.GetComponentsInChildren<Transform>();
//Debug.Log($"Total child count after:{children.Count()}, doors found:{doorsFound}");
return prefab;
}
private GameObject GetDoorShaderPrefab()
{
string[] shieldPrefab = AssetDatabase.FindAssets(c_doorShieldFxLocked);
//Debug.Assert(shieldPrefab.Length == 1, "Expected exactly 1 shield like this...");
string shieldGuid = shieldPrefab[0];
string prefabPath = AssetDatabase.GUIDToAssetPath(shieldGuid);
GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
//Debug.Assert(prefab != null, "Expected prefab to load");
return prefab;
}
private GameObject RemoveFunc(GameObject prefab)
{
var children = prefab.GetComponentsInChildren<Transform>();
//Debug.Log($"child count:{children.Count()}");
foreach (Transform trans in children)
{
if (trans.name.StartsWith(c_doorShieldFxLocked))
{
//Debug.Log("Found door shader");
DestroyImmediate(trans.gameObject);
}
}
children = prefab.GetComponentsInChildren<Transform>();
//Debug.Log($"child count:{children.Count()}");
return prefab;
}
private void Modify(GameObject parentPrefab, Func<GameObject,GameObject> modifyActionOnPrefab)
{
// Get the Prefab Asset root GameObject and its asset path.
string assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(parentPrefab);
// Load the contents of the Prefab Asset.
GameObject prefab = PrefabUtility.LoadPrefabContents(assetPath);
//PrefabUtility.UnpackPrefabInstance(mostPrefabInstanceRoot, PrefabUnpackMode.Completely, UnityEditor.InteractionMode.AutomatedAction);
prefab = modifyActionOnPrefab(prefab);
PrefabUtility.SaveAsPrefabAsset(prefab, assetPath);
PrefabUtility.UnloadPrefabContents(prefab);
}
}
I want to do it in the method DeleteAllShaders.
Now the function RemoveFunc will remove only the shaders childs that are under specific prefabs and parents.
I want to give a choice to destroy all the shaders in the world including shaders that are under prefabs.
Maybe to use the RemoveFunc but in this case I don't want to add a new shaders only to destroy.
I'm using AllParents flag to decide if to get all the doors left and right in the world or if to get the doors left and right under specific parents. When AllParents is true then I want to be able to delete all the shaders in the world those under any of the doors and those that not under any doors. All the shaders.

Related

Objects out of place Unity

I'm making an android 2D game on Unity 2020.3.30f1. I inserted a scroll view into the project, when the game starts, the content and buttons change size and the buttons flip. What should I do?
Maybe it has nothing to do with the code?
Thank you in advance!
Sorry if bad code.
Here's what it looks like:
It should be:
Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class AchMenu : MonoBehaviour
{
public int money;
public int total_money;
[SerializeField] bool isFirst;
public string[] arrayTitles;
public Sprite[] arraySprites;
public GameObject button;
public GameObject content;
private List<GameObject> list = new List<GameObject>();
private VerticalLayoutGroup _group;
void Start()
{
money = PlayerPrefs.GetInt("money");
total_money = PlayerPrefs.GetInt("total_money");
isFirst = PlayerPrefs.GetInt("isFirst") == 1 ? true : false;
RectTransform rectT = content.GetComponent<RectTransform>();
rectT.transform.localPosition = new Vector3(0.0f, 0.0f, 0.0f);
_group = GetComponent<VerticalLayoutGroup>();
setAchievs();
if (isFirst)
{
StartCoroutine(IdleFarm());
}
}
private void RemovedList()
{
foreach (var elem in list)
{
Destroy(elem);
}
list.Clear();
}
void setAchievs()
{
RectTransform rectT = content.GetComponent<RectTransform>();
rectT.transform.localPosition = new Vector3(0.0f, 0.0f, 0.0f);
RemovedList();
if (arrayTitles.Length > 0)
{
var pr1 = Instantiate(button, transform);
var h = pr1.GetComponent<RectTransform>().rect.height;
var tr = GetComponent<RectTransform>();
tr.sizeDelta = new Vector2(tr.rect.width, h * arrayTitles.Length);
Destroy(pr1);
for (var i = 0; i < arrayTitles.Length; i++)
{
var pr = Instantiate(button, transform);
pr.GetComponentInChildren<Text>().text = arrayTitles[i];
pr.GetComponentsInChildren<Image>()[1].sprite = arraySprites[i];
var i1 = i;
pr.GetComponent<Button>().onClick.AddListener(() => GetAchievement(i1));
list.Add(pr);
}
}
}
void GetAchievement(int id)
{
switch (id)
{
case 0:
Debug.Log(id);
break;
case 1:
Debug.Log(id);
money += 10;
PlayerPrefs.SetInt("money", money);
break;
case 2:
Debug.Log(id);
break;
}
}
IEnumerator IdleFarm()
{
yield return new WaitForSeconds(1);
money++;
Debug.Log(money);
PlayerPrefs.SetInt("money", money);
StartCoroutine(IdleFarm());
}
public void ToMenu()
{
SceneManager.LoadScene(0);
}
// Update is called once per frame
void Update()
{
}
}

Why the door/s colors flag is all the time true/false and all the time change between true and false?

This script is attached to a door :
Even if the variable doorLockState is set to true enabled true in the editor and the door should be color in red the door is green using a breakpoint the state variable inside ColorDoors is change between red and green non stop once state is true next it's false but in the editor it's all the time checked as true :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System;
[ExecuteAlways]
public class HoriDoorManager : MonoBehaviour
{
public List<DoorHori> doors = new List<DoorHori>();
public bool doorLockState;
private void Awake()
{
if (transform.parent != null)
{
Transform parent = transform.parent;
var children = parent.GetComponentsInChildren<Transform>();
if (children != null)
{
foreach (Transform door in children)
{
if (door.name == "Door_Left" || door.name == "Door_Right")
doors.Add(door.GetComponent<DoorHori>());
}
}
ColorDoors(Color.red, Color.green, doorLockState);
}
}
void OnTriggerEnter()
{
if (doorLockState == false)
{
if (doors != null)
{
for (int i = 0; i < doors.Count; i++)
{
doors[i].OpenDoor();
}
}
}
}
private void Update()
{
ColorDoors(Color.red, Color.green, doorLockState);
}
private void ColorDoors(Color red, Color green, bool state)
{
List<Transform> children = new List<Transform>();
for (int i = 0; i < doors.Count; i++)
{
foreach (Transform child in doors[i].GetComponentsInChildren<Transform>())
{
if (child == doors[i].transform)
continue;
var renderer = child.GetComponent<Renderer>();
renderer.sharedMaterial.shader = Shader.Find("Unlit/ShieldFX");
if (state == true)
{
renderer.sharedMaterial.SetColor("_MainColor", red);
LockState(true);
}
else
{
renderer.sharedMaterial.SetColor("_MainColor", green);
LockState(false);
}
}
}
}
public bool GetLockState
{
get { return doorLockState; }
set { doorLockState = value; }
}
private void LockState(bool state)
{
var collider = gameObject.GetComponent<BoxCollider>();
if (state == false)
{
collider.size = new Vector3(2.3f, 2.736307f, 2.5f);
collider.center = new Vector3(0, 1.378154f, 0);
collider.transform.localPosition = new Vector3(-1.57f, 0, -2.98f);
collider.isTrigger = true;
}
else
{
collider.size = new Vector3(2.3f, 2.736307f, 3);
collider.center = new Vector3(0, 1.378154f, 0);
collider.transform.localPosition = new Vector3(-1.57f, 0, -2.98f);
collider.isTrigger = false;
}
}
}
Screenshot of a door constructor in the Hierarchy and the script in the Inspector:
The object Horizontal_Doors_Kit tag is set to Door.
And this is the editor script that should let me control the doors but there is also a problem here too since in the editor it's not listing all the doors :
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(DoorsLockManager))]
public class DoorsLockManagerEditor : Editor
{
private SerializedProperty _doors;
private SerializedProperty _globalLockState;
private bool shouldOverwrite;
private void OnEnable()
{
_doors = serializedObject.FindProperty("Doors");
_globalLockState = serializedObject.FindProperty("_globalLockState");
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
serializedObject.Update();
shouldOverwrite = false;
// Begin a change check here
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(_globalLockState);
if (EditorGUI.EndChangeCheck())
{
// overwrite only once if changed
shouldOverwrite = true;
}
for (int i = 0; i < _doors.arraySize; i++)
{
var door = _doors.GetArrayElementAtIndex(i);
// if door == null the script itself has an error since it can't even find the SerializedProperty
if (door == null)
{
EditorGUILayout.HelpBox("There was an error in the editor script!\nPlease check the log", MessageType.Error);
Debug.LogError("Couldn't get door property", target);
return;
}
if (door.objectReferenceValue == null) continue;
var serializedDoor = new SerializedObject(door.objectReferenceValue);
var lockState = serializedDoor.FindProperty("doorLockState");
serializedDoor.Update();
if (lockState == null)
{
EditorGUILayout.HelpBox("There was an error in the editor script!\nPlease check the log", MessageType.Error);
Debug.LogError("Couldn't get lockState property", target);
return;
}
// HERE OVERWRITE
if (shouldOverwrite)
{
lockState.boolValue = _globalLockState.boolValue;
}
else
{
EditorGUILayout.PropertyField(lockState, new GUIContent("Door " + i + " Lockstate"));
}
serializedDoor.ApplyModifiedProperties();
}
serializedObject.ApplyModifiedProperties();
}
}
Screenshot of the editor script inspector :
It's showing the two variables Global Lock State but it should also list the 12 doors.
The first problem the state of the door/s is all the time unlocked green color.
The second problem is why it's not listing all the doors so I can control each/all the doors either in editor or runtime ?
And the script DoorsLockManager :
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class DoorsLockManager : MonoBehaviour
{
[HideInInspector]
public List<HoriDoorManager> Doors = new List<HoriDoorManager>();
// The global state
[SerializeField] private bool _globalLockState;
// During runtime use a property instead
public bool GlobalLockState
{
get { return _globalLockState; }
set
{
_globalLockState = value;
// apply it to all doors
foreach (var door in Doors)
{
// now you would need it public again
// or use the public property you had there
door.doorLockState = _globalLockState;
}
}
}
private void Awake()
{
var doors = GameObject.FindGameObjectsWithTag("Door");
Doors = new HoriDoorManager[doors.Length].ToList();
for (int i = 0; i < doors.Length; i++)
{
Doors[i] = doors[i].GetComponent<HoriDoorManager>();
}
}
}
Currently your Doors list is only being updated when Awake() is called in your DoorsLockManager (and not accessible from the inspector), which means the list is always empty outside of runtime. Changing this should allow the list to be displayed in the inspector while editing.
Making the following minor changes to DoorsLockManager.cs:
private void Awake()
{
UpdateDoors();
}
public void UpdateDoors()
{
var doors = GameObject.FindGameObjectsWithTag("Door");
Doors = new HoriDoorManager[doors.Length].ToList();
for (int i = 0; i < doors.Length; i++)
{
Doors[i] = doors[i].GetComponent<HoriDoorManager>();
}
}
and adding the following to the top of the OnInspectorGUI() method in DoorsLockManagerEditor.cs:
if (GUILayout.Button("Update Door List"))
{
((DoorsLockManager)target).UpdateDoors();
}
should achieve this by providing a button to update the list when needed.
Individual and global lock states should now be functional, however only one of the two Global Lock State toggles is properly functional, this can be fixed by either removing base.OnInspectorGUI(); from the OnInspectorGUI() method in DoorsLockManagerEditor.cs or by adding [HideInInspector] before [SerializeField] private bool _globalLockState; in DoorsLockManager.cs.
Currently HoriDoorManager.cs will only update their respective doors at runtime as the ColorDoors method is called only in Awake() and Update(). This can instead be made to update whenever the doorLockState bool is changed by modifying your GetLockState property as so:
public bool GetLockState
{
get { return doorLockState; }
set
{
doorLockState = value;
ColorDoors(Color.red, Color.green, doorLockState);
}
}
and assigning to this property instead of the backing variable in the GlobalLockState property of DoorsLockManager.cs (replacing line 28: door.doorLockState = _globalLockState; with door.GetLockState = _globalLockState;).
Edit:
This is a bit of a quick hack but adding the following to DoorsLockManager.cs:
public void UpdateColors()
{
foreach (var door in Doors)
{
door.GetLockState = door.GetLockState;
}
}
and the following to OnInspectorGUI() in DoorsLockManagerEditor.cs beneath the other button:
if (GUILayout.Button("Update Door Colors"))
{
((DoorsLockManager)target).UpdateColors();
}
should allow you to tell the doors to update their colours from the inspector manually.

How to scale only one game object in the AR scene in Unity?

so I have like 5 game object in my scene but I only scale each of them separately. However when I try to do that all of them start scaling simultaneously. Also, I have a placement indicator that would be used to instantiate the object on the plane. It seems that instead of the object itself, the placement indicator is the one that gets scaled. How should I fix that?
I have tried deactivating the placement indicator but did not work.
Here is the code for instantiating objects:
I limited the obj number to 5.
I use this script instead of the usual "PlaceonPlane" script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.Experimental.XR;
using UnityEngine.UI;
using UnityEngine.XR.ARSubsystems;
public class ARTaptoPlaceObject : MonoBehaviour
{
private ARSessionOrigin arOrigin;
GameObject spawnedobj;
public GameObject placementIndicator;
private ARRaycastManager arRaycast;
public Pose placementPose;
public UIContoller sc;
public bool placementPoseIsValid = false;
private int count;
private string valu;
string prefabs;
void Start()
{
arOrigin = FindObjectOfType<ARSessionOrigin>();
arRaycast = FindObjectOfType<ARRaycastManager>();
count = 0;
}
// Update is called once per frame
void Update()
{
UpdatePlacementPose();
UpdatePlacementIndicator();
for (var i = 0; i < Input.touchCount; ++i)
{
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
if (placementPoseIsValid && Input.GetTouch(i).tapCount == 2)
{
PlaceObject();
}
}
}
}
public void PlaceObject()
{
if (count <= 4)
{
if (sc.objectToPlace != null)
{
spawnedobj = Instantiate(sc.objectToPlace, placementPose.position, placementPose.rotation);
arOrigin.MakeContentAppearAt(spawnedobj.transform, spawnedobj.transform.position, spawnedobj.transform.rotation);
count++;
}
}
else
{
placementIndicator.SetActive(false);
}
}
private void UpdatePlacementIndicator()
{
if (placementPoseIsValid && count <= 4 && sc.active == false)
{
placementIndicator.SetActive(true);
placementIndicator.transform.SetPositionAndRotation(placementPose.position, placementPose.rotation);
}
else
{
placementIndicator.SetActive(false);
}
}
private void UpdatePlacementPose()
{
var screenCenter = Camera.current.ViewportToScreenPoint(new Vector3(0.5f, 0.5f));
var hits = new List<ARRaycastHit>();
arRaycast.Raycast(screenCenter, hits, UnityEngine.XR.ARSubsystems.TrackableType.Planes);
placementPoseIsValid = hits.Count > 0;
if (placementPoseIsValid)
{
placementPose = hits[0].pose;
var cameraForward = Camera.current.transform.forward;
var cameraBearing = new Vector3(cameraForward.x, 0, cameraForward.z).normalized;
placementPose.rotation = Quaternion.LookRotation(cameraBearing);
}
}
}
and here is the Scaler script that's attached to the button that would scale the object.
public class Scaler : MonoBehaviour
{
public UIContoller uc;
public ARTaptoPlaceObject ap;
private GameObject ReferenceToScale;
public void OnValueChange()
{
ReferenceToScale = (UnityEngine.GameObject)Resources.Load(uc.s_count, typeof(GameObject));
Vector3 t = ReferenceToScale.transform.localScale;
Vector3 scaleValue = t * 1.1f;
ReferenceToScale.transform.localScale = scaleValue;
}
Also the "objectToPlace" itself is in the "UI.Controller" script as I could not view it in the scene when it was in the "ARTaptoPlace" script

How can i make clone object invisible Unity

1.i have an issue when i start dragging object its clonning itself, i need that in panel zone(my object respawning in there) not in dropzone im trying to find solution for this can i make clone invisible? if i can how ?here is the code :
enter code here
public class DragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public enum Slot { ileri, sağa, sola, fonksiyon };
public Slot typeofMove;
public Transform ParentreturnTo = null;
public Transform PlaceholderParent = null;
GameObject placeholder = null;
public GameObject ileriprefab;
public GameObject x;
public GameObject panel;
public void OnBeginDrag(PointerEventData eventData)
{
placeholder = new GameObject();
placeholder.transform.SetParent(this.transform.parent);
LayoutElement le = placeholder.AddComponent<LayoutElement>();
le.preferredWidth = this.GetComponent<LayoutElement>().preferredWidth;
le.preferredHeight = this.GetComponent<LayoutElement>().preferredHeight;
le.flexibleWidth = 0;
le.flexibleHeight = 0;
placeholder.transform.SetSiblingIndex(this.transform.GetSiblingIndex());
//sibling index kartı aldıgımız yeri döndürür.
Debug.Log("OnBeginDrag");
ParentreturnTo = this.transform.parent;
PlaceholderParent = ParentreturnTo;
this.transform.SetParent(this.transform.parent.parent);
if (this.transform.parent.position == GameObject.FindGameObjectWithTag("carddroparea").transform.position)
{
x = Instantiate(moveforwardprefab, moveforvardprefab.transform.position, Quaternion.identity);
x.transform.SetParent(PlaceholderParent.transform);
//im trying to saying here if the object "this" in drop zone dont instantiate it or make it invisible ??????? but its not working
}
GetComponent<CanvasGroup>().blocksRaycasts = false;
}
public void OnDrag(PointerEventData eventData)
{
Debug.Log("OnDrag");
this.transform.position = eventData.position;
if (placeholder.transform.parent != PlaceholderParent)
placeholder.transform.SetParent(PlaceholderParent);
int newSiblingIndex = PlaceholderParent.childCount;
for (int i = 0; i < PlaceholderParent.childCount; i++)
{
//**parentreturnto. getchild(i)**//
if (this.transform.position.x < PlaceholderParent.GetChild(i).position.x)
{
newSiblingIndex = i;
// placeholder.transform.SetSiblingIndex(i);
if (PlaceholderParent.transform.GetSiblingIndex() < newSiblingIndex)
newSiblingIndex--;
break;
}
}
placeholder.transform.SetSiblingIndex(newSiblingIndex);
}
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("OnEndDrag");
this.transform.SetParent(ParentreturnTo);
this.transform.SetSiblingIndex(placeholder.transform.GetSiblingIndex());
//Kartın alındıgı yere konulması için gerekli
GetComponent<CanvasGroup>().blocksRaycasts = true;
Destroy(placeholder);
if (this.transform.parent.position == GameObject.FindGameObjectWithTag("panel").transform.position)
{
Destroy(x);
Debug.Log("destroyed");
}
if (x.transform.parent.position == GameObject.FindGameObjectWithTag("carddroparea").transform.position)
{
Destroy(x);
Debug.Log("destroyed");
}
}
}
If you just want to make a GameObject invisible there are many ways to do it.
You can, for example:
yourGameObject.SetActive(false);
You can also deactivate your gameobject Renderer
yourGameObject.GetComponent<Renderer>().enabled = false;
how to adapt it to your code is up to you.

How to reference a class from child to parent?

It may sound stupid but how can i reference a class from one script in child in another script in parent? I cant find anything on google. Note: There are couple errors in my script, that's not the point of the post.
//Public
//Private
private Rigidbody myRigidbody;
private Renderer myRenderer;
private Material tileDefaultMaterial;
private Material tileSelectedMaterial;
private Material tileSameGroupMaterial;
void Start () {
myRigidbody = GetComponent<Rigidbody> ();
myRenderer = GetComponent<Renderer> ();
tileDefaultMaterial = Resources.Load ("TileDefault", typeof(Material)) as Material;
tileSelectedMaterial = Resources.Load ("TileSelected", typeof(Material)) as Material;
tileSameGroupMaterial = Resources.Load ("TileSameGroup", typeof(Material)) as Material;
}
void Update () {
}
public class TileClass {
public int tileGroup = 0; //Indicates the Tile Group Number.
}
//Public
public GameObject[] allTiles; //Aray of all Tile GameObject.
public bool tileIsSelected = false; //If a Tile is Selected.
public int selectedTileGroup = 0; //Indicates the Selected Tile Group Number.
public int tileGroup = 0; //Indicates the Tile Group Number.
//Private
void Start () {
allTiles = new GameObject[transform.childCount];
for(int i = 0; i < transform.childCount; i++){
allTiles [i] = transform.GetChild (i).gameObject;
}
}
void Update () {
}
void OnMouseDown (){
RaycastHit hitInfo = new RaycastHit ();
bool hit = Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hitInfo);
if (hitInfo.transform.gameObject.tag == "Tile" && tileIsSelected == false) {
Debug.Log ("A Tile is Selected!");
tileIsSelected = true;
selectedTileGroup = ;
for(int i = 0; i < allTiles.Length; i++){
if (this.tileGroup == selectedTileGroup) {
allTiles [i].GetComponent<Renderer> ().material = tileSameGroupMaterial;
}
}
myRenderer.material = tileSelectedMaterial;
} else if (hitInfo.transform.gameObject.tag == "Tile" && tileIsSelected == true) {
Debug.Log ("Second Tile is Clicked! (Should Swap them!)");
myRenderer.material = tileDefaultMaterial;
}
}
There is a famous saying :
var allTiles = transform.GetComponentsInChildren<Tile>();
And as I told you yesterday, Add OnMouseDown() in Tile.cs and write myRenderer.material = tileDefaultMaterial; there. No need to write this in TileManager.cs. And NO need to use Raycast when using OnMouseDown().
I can't read your image code, so I'll make up my own class names for the example. I'll call the parent class TileManager and the child class Tile.
Say in Tile you want access to the array of tiles in the TileManager. If allTiles is declared as public, you'd do in Tile somewhere.
TileManager tileManager = transform.parent.GetComponent<TileManager>();
var allTiles = tileManager.allTiles;
Now the Tile child has a reference to the array. Was this what you were wanting?
how about base.Method?
That should do it

Categories