Hiding Clone Game Object with Tag - c#

I got an error while trying hiding and showing a group of clone object with tag. the clone is dynamic(position). I have toggle to visible and visible some information text. Now I want to hide and unhide the game object with tag. ("windtag"). Also tryna hiding those gameobject in arrow method.
public GameObject[] test;
public void invisible(bool log)
{
test= GameObject.FindGameObjectsWithTag("windtag");
test.GetComponent<Renderer>().enabled = log;
}
public void clone()
{
Canvas newcanvas = Instantiate(canvas);
//Use .SetParent(canvasName,false)
Text cloneposition = Instantiate(shiposition, newpos);
Text clonewind = Instantiate(windspeedtext, newpos);
Text clonedlow = Instantiate(flowtext, newpos);
Text clonetemperature = Instantiate(temperaturetext, newpos);
newcanvas.transform.position = shipvalue.transform.position;
cloneposition.transform.SetParent(newcanvas.transform, false);
clonewind.transform.SetParent(newcanvas.transform, false);
clonedlow.transform.SetParent(newcanvas.transform, false);
clonetemperature.transform.SetParent(newcanvas.transform, false);
clonewind.gameObject.SetActive(false);
clonetemperature.gameObject.SetActive(false);
}
public void arrow(float[,] arrowdata)
{
for (int x = 0; x < arrowdata.GetLength(0); x++)
{
for (int y = 0; y < arrowdata.GetLength(1); y++)
{
if (grid[x,y] ==1)
{
if (arrowdata[x, y] == 5)
{
GameObject referenceArrow = Instantiate(Resources.Load("down")) as GameObject;
float posY = shipvalue.transform.position.y - 9f;
referenceArrow.transform.position = new Vector3(shipvalue.transform.position.x-0.5f, posY);
}
if (arrowdata[x, y] == 4)
{
GameObject referenceArrow = Instantiate(Resources.Load("top left")) as GameObject;
float posY = shipvalue.transform.position.y - 9f;
referenceArrow.transform.position = new Vector3(shipvalue.transform.position.x - 0.5f, posY);
}
if (arrowdata[x, y] == 3)
{
GameObject referenceArrow = Instantiate(Resources.Load("top right")) as GameObject;
float posY = shipvalue.transform.position.y - 9f;
referenceArrow.transform.position = new Vector3(shipvalue.transform.position.x - 0.5f, posY);
}
}
}
}
}
this is the error :
Severity Code Description Project File Line Suppression State
Error CS1061 'GameObject[]' does not contain a definition for 'GetComponent' and no accessible extension method 'GetComponent' accepting a first argument of type 'GameObject[]' could be found (are you missing a using directive or an assembly reference?) Assembly-CSharp C:\Users\Skylarking\Unity\My First Game\MyFirstGame\Assets\Scripts\test.cs 391 Active

I think your current problem is that there is more than one Object with the Tag "windtag". So if you search for GameObject with that tag more than one is returned. Resulting in a GameObject Array instead of one GameObject.
An easy fix could be to add different Tags to all GameObject and then giving that string to the function.
invisible(false, "tagexample1");
public void invisible(bool log, string tag)
{
test= GameObject.FindGameObjectWithTag(tag);
test.GetComponent<Renderer>().enabled = log;
}
Or you could put your GetComponent<Renderer>() into a for loop. To hide/show all elements with the windtag. If that is what you want.
public void invisible(bool log)
{
test= GameObject.FindGameObjectsWithTag("windtag");
foreach (GameObject gm in test){
gm.GetComponent<Renderer>().enabled = log;
}
}

Related

How to get Panel to show when character lands on a specific position on game board after dice roll in Unity

I have a 3D board game in Unity. I would like to move my character without having to press a key, but most importantly I would like to show a dynamic panel in canvas for whatever square the character lands on. So far I have the dice rolling and the character moving (after pressing a key) the correct amount of squares, but I am unable to figure out how to activate the panel based on the square color. Any help would be appreciated.
Here is my CharacterScript:
public class CharacterScript : MonoBehaviour
{
public Path currentPath;
public int squarePosition;
public int squares;
bool isMoving;
public GameObject PinkSquarePanel = GameObject.FindGameObjectWithTag("PinkSquare");
public GameObject CyanSquarePanel = GameObject.FindGameObjectWithTag("CyanSquare");
public GameObject WhiteSquarePanel = GameObject.FindGameObjectWithTag("WhiteSquare");
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape) && !isMoving)
{
squares = DiceNumberTextScript.diceNumber;
}
StartCoroutine(Move());
if (squares == 0)
{
ActivateSquarePanel();
}
}
IEnumerator Move()
{
if (isMoving)
{
yield break;
}
isMoving = true;
while (squares > 0)
{
Vector3 nextPosition = currentPath.squareList[squarePosition + 1].position;
while (MoveToNextSquare(nextPosition))
{
yield return null;
}
yield return new WaitForSeconds(0.1f);
squares--;
squarePosition++;
}
isMoving = false;
}
bool MoveToNextSquare(Vector3 goal)
{
return goal != (transform.position = Vector3.MoveTowards(transform.position, goal, 4f * Time.deltaTime));
}
void ActivateSquarePanel()
{
if (squarePosition.Equals(PinkSquarePanel))
{
PinkSquarePanel.GetComponent<CanvasGroup>().alpha = 1;
}
else if (squarePosition.Equals(CyanSquarePanel))
{
CyanSquarePanel.GetComponent<CanvasGroup>().alpha = 1;
}
else if (squarePosition.Equals(WhiteSquarePanel))
{
WhiteSquarePanel.GetComponent<CanvasGroup>().alpha = 1;
}
}
}
And here is my PathScript:
public class Path : MonoBehaviour
{
Transform[] squareObjects;
public List<Transform> squareList = new List<Transform>();
GameObject[] PinkSquares = GameObject.FindGameObjectsWithTag("PinkSquare");
PinkSquare[] pinkList = new PinkSquare[1];
GameObject[] CyanSquares = GameObject.FindGameObjectsWithTag("CyanSquare");
CyanSquare[] cyanList = new CyanSquare[1];
GameObject[] WhiteSquares = GameObject.FindGameObjectsWithTag("WhiteSquare");
WhiteSquare[] whiteList = new WhiteSquare[1];
private void OnDrawGizmos()
{
Gizmos.color = Color.black;
FillSquares();
for (int i = 0; i < squareList.Count; i++)
{
Vector3 currentPosition = squareList[i].position;
if (i > 0)
{
Vector3 previousPosition = squareList[i - 1].position;
Gizmos.DrawLine(previousPosition, currentPosition);
if(currentPosition.Equals(PinkSquares))
{
pinkList[i] = new PinkSquare();
}
else if (currentPosition.Equals(CyanSquares))
{
cyanList[i] = new CyanSquare();
}
else if (currentPosition.Equals(WhiteSquares))
{
whiteList[i] = new WhiteSquare();
}
}
}
}
void FillSquares()
{
squareList.Clear();
squareObjects = GetComponentsInChildren<Transform>();
foreach (Transform square in squareObjects)
{
if (square != this.transform)
{
squareList.Add(square);
}
}
}
}
I believe your issue is in your comparisons, you are trying to use an Equals to compare your currentPosition which is a Vector3 type to a GameObject[] which is an array of gameObjects. As I mentioned in my comments, this comparison will always fail as an array of gameObjects can not be equal to a vector.
Instead of using these lines, try this line:
if(squareList[i].gameObject.tag.CompareTag("PinkSquare")
The full snippet of if else would look like
if(squareList[i].gameObject.tag.CompareTag("PinkSquare")
{
pinkList[i] = new PinkSquare();
}
else if(squareList[i].gameObject.tag.CompareTag("CyanSquare")
{
cyanList[i] = new CyanSquare();
}
else if(squareList[i].gameObject.tag.CompareTag("WhiteSquare")
{
whiteList[i] = new WhiteSquare();
}
Your CharacterScript is going to need to get the gameObject or Transform from the Path script as it is only keeping track of indexes. Your issue in this script is you are comparing an integer to a GameObject which would never be true. I would also recommend not using OnDrawGizmos() as it is an editor only script and should only be used to render editor debugging tools. The only reference to a Gizmo I see in the function is Gizmos.color = Color.black; which does nothing as you are not rendering a gizmo anywhere. I would move this code to a different function and call it from your CharacterScript. Have the return type be GameObject or Transform of the square you are on, so the CharacterSCript can check which color it lands on. Using an Integer nor Vector3 to compare to a GameObject[] will never work.
I am not sure if there are issues elsewhere in the code, but as this comparison would always fail, none of these statements would get broken into. What this means is your panels would never have the chance to get their alpha set nor get created.

When I die, a heart doesn't get removed, but no errors

I'm creating a 2d runner and i have this "collision.cs" file that I have my heart system in, I don't get any errors but when I die a heart doesn't get removed so what am I doing wrong?
The system is based on tags so I tried changing the tag system a lot but nothing worked; then I tried to change the way I find the gameobject after a while I saw that it was creating a lot off gameobjects instead of 3 so I tried to change the tag system around that but even that didn't work and I really don't want to have a plain text that says 3 lives etc.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Collision : MonoBehaviour {
public int lifes = 3 ;
//public GameObject Life_icon1;
//public GameObject Life_icon2;
//public GameObject Life_icon3;
public Sprite Heart;
public int current_icon = 3;
public GameObject ParentPanel;
public static int Coins = 0;
public float offset = 150f;
List<int> i = new List<int>() { 1 };
public int tagN;
void Update() {
tagN = i.Max() + 1;
}
// Use this for initialization
void Start () {
for(int x = 0; x < lifes; x++)
{
i.Add(x);
GameObject NewObj = new GameObject(); //Create the GameObject
Image NewImage = NewObj.AddComponent<Image>(); //Add the Image Component script
NewImage.gameObject.tag = x.ToString();
if(x == 0) {
NewImage.transform.position = new Vector3(0 + 40f, 0 + 40f , 0);
} else {
NewImage.transform.position = new Vector3(0 + offset, 0 + 40f , 0);
offset += 130f;
}
//print(x);
NewImage.sprite = Heart; //Set the Sprite of the Image Component on the new GameObject
NewObj.GetComponent<RectTransform>().SetParent(ParentPanel.transform); //Assign the newly created Image GameObject as a Child of the Parent Panel.
NewObj.SetActive(true); //Activate the GameObject
}
}
void AddLife(int amount) {
lifes++;
i.Add(amount);
GameObject NewObj = new GameObject(); //Create the GameObject
NewObj.gameObject.tag = tagN.ToString();
Image NewImage = NewObj.AddComponent<Image>(); //Add the Image Component script
NewImage.transform.position = new Vector3(0 + offset, 0 + 40f , 0);
NewImage.sprite = Heart; //Set the Sprite of the Image Component on the new GameObject
NewObj.GetComponent<RectTransform>().SetParent(ParentPanel.transform); //Assign the newly created Image GameObject as a Child of the Parent Panel.
NewObj.SetActive(true); //Activate the GameObject
}
void DelLife(int amount) {
Vector3 pos = transform.position;
offset -= 130f;
pos.x = -0.49f;
pos.y = -0.49f;
transform.position = pos;
i.RemoveAt(i.Max());
GameObject go = null;
if (GameObject.FindWithTag(tagN.ToString()) != null)
{
go = GameObject.FindWithTag(tagN.ToString());
}
if (go != null)
{
go.gameObject.SetActive(false);
}
}
void OnTriggerEnter2D(Collider2D other)
{
//extra life item collision
if(other.gameObject.name == "Heart_item") {
AddLife(1);
Destroy(other.gameObject);
}
if(other.gameObject.name == "Spike") {
DelLife(1);
}
if(other.gameObject.name == "Coin") {
Destroy(other.gameObject);
Coins += 1;
}
}
}

Move Gameobject generating Objects based on Data

I am generating gameobjects (spheres) based on coordinates, which are stored in a .csv file. I have a Gameobject with a Single Sphere as primitive childobject. Based on the data the Object will clone this sphere 17 times and move them around. I can move the whole thing around like i want it to by accessing the parent object, but in editing mode the position of the root sphere makes it uneasy to use.
The following Code makes this possible.
public GameObject parentObj;
public TextAsset csvFile;
[SerializeField]
private float scaleDownFactor = 10;
private int index = 0;
//class Deck : MonoBehaviour
//{
[SerializeField]
private GameObject[] deck;
private GameObject[] instanciatedObjects;
private void Start()
{
Fill();
}
public void Fill()
{
instanciatedObjects = new GameObject[deck.Length];
for (int i = 0; i < deck.Length; i++)
{
instanciatedObjects[i] = Instantiate(deck[i]) as GameObject;
}
}
//}
// Update is called once per frame
void Update()
{
readCSV();
}
void readCSV()
{
string[] frames = csvFile.text.Split('\n');
int[] relevant = {
0
};
string[] coordinates = frames[index].Split(',');
for (int i = 0; i < 17; i++)
{
float x = float.Parse(coordinates[relevant[i] * 3]) / scaleDownFactor;
float y = float.Parse(coordinates[relevant[i] * 3+1]) / scaleDownFactor;
float z = float.Parse(coordinates[relevant[i] * 3+2]) / scaleDownFactor;
//objectTest.transform.Rotate(float.Parse(fields[1]), float.Parse(fields[2]), float.Parse(fields[3]));
//objectTest.transform.Translate(x, y, z);
//parentObj.transform.position = new Vector3(x, y, z);
instanciatedObjects[i].transform.position = new Vector3(parentObj.transform.position.x, parentObj.transform.position.y, parentObj.transform.position.z);
instanciatedObjects[i].transform.eulerAngles = new Vector3(parentObj.transform.eulerAngles.x, parentObj.transform.eulerAngles.y, parentObj.transform.eulerAngles.z);
//instanciatedObjects[i].transform.position = new Vector3(x, y, z);
instanciatedObjects[i].transform.Translate(x, y, z);
}
if (index < frames.Length - 1)
{
index++;
}
if (index >= frames.Length -1)
{
index = 0;
}
}
Here is a Screenshot:
So my question is:
How can I set the Position of this Sphere to one of the moving points, without changing the position of the cloned objects? Since all behave based on the BaseSphere?
Is it possible to make the BaseSphere not visible While the Objects are getting cloned or generated?
I am looking for a solution, that makes it easier to move the datagenerated Object around in Editor.
I would appreciate any kind of input.
Make all Spheres children of Empty Gameobject (for example. Sphere_root) and use this for moving Spheres.
Also check Scriptable Objects. It is simple and very quick method to manage data in Unity.
#Edit
public void Fill()
{
instanciatedObjects = new GameObject[deck.Length];
for (int i = 0; i < deck.Length; i++)
{
instanciatedObjects[i] = Instantiate(deck[i]) as GameObject;
instanciatedObjects[i].transform.parent = Baumer; // or Sphere Root or somehing else.
}
}

photon rpc is not calling correctly(Photon RPC with character generating)

I'm trying to generate character with script.
I have 'playerObj' and 'model' pref under resource folder. playerObj has all the script related controlling, and photonView, Camera, etc. and model has animation, skin renderer, and photonView.
What am I trying to do is, instantiating playerObj and instantiating model object together. and with model obj, I want to add some skin mesh so it has character's model (I did this so player is able to change model's outfit) and then parenting playerObj with model.
Problem is it did instantiating own character correctly, but the instantiating other character is wrong.
it will instantiating both playerObj and model Obj. but it doesn't rendering skin mesh and doesn't parenting those two...
I don't know what i did wrong or missing something...
as you see down of the script i'm using three different script to generate character.
Thank you.
PlayerInit.cs
public IEnumerator CreateCharacter()
{
var co = CurrentCharacter.GetByGUI(dbid);
co.InitModel(character, dbid);
m_loaded = true;
m_loading = false;
}
CharacterGenerator.cs
public GameObject Generate(PhotonView pv)
{
int id1 = PhotonNetwork.AllocateViewID();
GameObject root = PhotonNetwork.Instantiate ("Model", new Vector3 (0, 0, 0), new Quaternion (0, 0, 0, 0),0);
root.name = "body";
Generate (pv, root);
return root;
}
public GameObject Generate(PhotonView pv, GameObject root)
{
int id1 = PhotonNetwork.AllocateViewID();
putSkin (root);
pv.RPC("putSkin", PhotonTargets.Others, root, id1, PhotonNetwork.player);
return root;
}
// Creates a character based on the currentConfiguration recycling a
// character base, this way the position and animation of the character
// are not changed.
[RPC]
public void putSkin(GameObject root){
float startTime = Time.realtimeSinceStartup;
// The SkinnedMeshRenderers that will make up a character will be
// combined into one SkinnedMeshRenderers using multiple materials.
// This will speed up rendering the resulting character.
List<CombineInstance> combineInstances = new List<CombineInstance>();
List<Material> materials = new List<Material>();
List<Transform> bones = new List<Transform>();
Transform[] transforms = root.GetComponentsInChildren<Transform>();
foreach (CharacterElement element in currentConfiguration.Values)
{
SkinnedMeshRenderer smr = element.GetSkinnedMeshRenderer();
materials.AddRange(smr.materials);
for (int sub = 0; sub < smr.sharedMesh.subMeshCount; sub++)
{
CombineInstance ci = new CombineInstance();
ci.mesh = smr.sharedMesh;
ci.subMeshIndex = sub;
combineInstances.Add(ci);
}
// As the SkinnedMeshRenders are stored in assetbundles that do not
// contain their bones (those are stored in the characterbase assetbundles)
// we need to collect references to the bones we are using
foreach (string bone in element.GetBoneNames())
{
foreach (Transform transform in transforms)
{
if (transform.name != bone) continue;
bones.Add(transform);
break;
}
}
Object.Destroy(smr.gameObject);
}
// Obtain and configure the SkinnedMeshRenderer attached to
// the character base.
SkinnedMeshRenderer r = root.GetComponent<SkinnedMeshRenderer>();
r.sharedMesh = new Mesh();
r.sharedMesh.CombineMeshes(combineInstances.ToArray(), false, false);
r.bones = bones.ToArray();
r.materials = materials.ToArray();
r.useLightProbes = true;
Debug.Log("Generating character took: "
+ (Time.realtimeSinceStartup - startTime) * 1000 + " ms");
}
CurrentCharacter.cs
[PunRPC]
public void InitModel(GameObject prefab, GameObject model, int id){
character = prefab;
InitModel (model, id);
}
public void InitModel(GameObject model, int id)
{
parenting (model, id);
_photonView.RPC ("parenting", PhotonTargets.Others, model, id);
}
[RPC]
void parenting(GameObject model, int id){
model.layer = LayerMask.NameToLayer ("Girl");
model.transform.parent = character.transform;
model.transform.localPosition = Vector3.zero;
InitMouseLook (model);
InitAnimations (model);
if (id == PersistentData.Instance.LoggedInUser.m_id) {
CurrentCharacter.persistentMainModel = model;
}
}

Return an ArrayList of GameObjects and grid issue

I was trying to generate a grid Unity3d and store all the tiles in an array. I want to use the created array also in others function.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class createGridClean : MonoBehaviour {
public GameObject tilePrefab = null;
public int numberOfTiles = 10;
public int tilesPerColumn = 4;
public float distanceBetweenTiles = 2.0f;
public Material newmat = null;
// Use this for initialization
void Start () {
CreateTiles ();
}
// Update is called once per frame
void Update () {
}
public ArrayList[] CreateTiles(){
GameObject[] allTiles = new GameObject[numberOfTiles*tilesPerColumn];
float xOffset = 0.0f;
float zOffset = 0.0f;
for (int createdTiles = 0; createdTiles <= numberOfTiles; createdTiles++) {
xOffset += distanceBetweenTiles;
if ( createdTiles % tilesPerColumn == 0){
zOffset += distanceBetweenTiles;
xOffset = 0.0f;
}
allTiles[createdTiles] = Instantiate (tilePrefab, new Vector3 (0f + xOffset, 0f, 0f + zOffset), Quaternion.identity) as GameObject;
}
return allTiles;
}
}
But here's the output:
Assets/my/Script/createGridClean.cs(34,17): error CS0029: Cannot implicitly convert type `UnityEngine.GameObject[]' to `System.Collections.ArrayList[]'
I have have even a problem with the grid, everytime an additional and unwanted extra cube were generated!
(here the original code that I've translated in C#)
function CreateTiles()
{
var xOffset: float = 0.0;
var zOffset: float = 0.0;
for(var tilesCreated: int = 0; tilesCreated < numberOfTiles; tilesCreated += 1)
{
xOffset += distanceBetweenTiles;
if(tilesCreated % tilesPerRow == 0)
{
zOffset += distanceBetweenTiles;
xOffset = 0;
}
Instantiate(tilePrefab, Vector3(transform.position.x + xOffset, transform.position.y, transform.position.z + zOffset), transform.rotation);
}
}
Any help will be fantastic!
Thanks,
Marco
Try changing
public ArrayList[] CreateTiles()
{
GameObject[] allTiles = new GameObject[numberOfTiles*tilesPerColumn];
...
return allTiles;
}
to:
public GameObject[] CreateTiles()
{
GameObject[] allTiles = new GameObject[numberOfTiles*tilesPerColumn];
...
return allTiles;
}
The error message you're getting: Cannot implicitly convert type X to Y refers to the fact that you're implicitly converting your GameObject[] to an ArrayList[]. You must either explicitly cast to an ArrayList[] (e.g. return (ArrayList[]) allTiles, although I'm not sure that's what you're after), or change your method to return a GameObject[].
Your question is a duplicate of all these other questions: https://stackoverflow.com/search?q=cannot+implicitly+convert

Categories

Resources