how to delete only one clone of a game object - c#

For example I have coin1(clone) and coin1(clone)(clone). If I click coin1(clone)(clone) it will be destroyed. But in my case, when I click coin1(clone)(clone), coin1(Clone) is deleted.
Codes I've been using
void NumberOfSelectedCoins()
{
Debug.Log (BlueCoinScript.b);
if(SelectedCoins.cntCoins%BlueCoinScript.b == 0)
{
for (int n=0;n<selectC.selectedNumCoins.Count; n++)
{
Destroy(selectC.selectedNumCoins[n]);
TotalSum.totalValue = 0;
SelectedCoins.breakPointsCount++;
}
breakpointsText.text = SelectedCoins.breakPointsCount.ToString ();
selectC.selectedNumCoins.Clear();
}
}
And also if you have 1 game object and you cloned it so that you can have 3 same game objects, how can you identify that when you clicked that game object, that game object is clone1 or clone2 or clone3?

You can for example identify GameObject instances by Object.GetInstanceID() or by Object.name. In the latter case though you have to take care that the object you search for is named and that this name is unique.
Further reference is found here.

Related

VR: Put item in hand from List

I hope you are doing well.
So I am creating a VR with XR game in which I have a list of items as Scriptable Objects. Now I want to put one item in my hand when I press a button but I run into problems because my function is not doing the right thing. This is how it looks like:
public void PutItemInHand()
{
for (int i = 0; i < inventoryItems.Count; i++)
{
if (inventoryItems[i].name == "Sword")
{
Instantiate(inventoryItems[i], handSpawn.position, handSpawn.rotation);
}
else if (inventoryItems[i].name == "Gun")
{
Instantiate(inventoryItems[i], handSpawn.position, handSpawn.rotation);
}
}
}
Also it says: "Cannot instantiate a ScriptableObject with a position and rotation".
Do you guys have an idea? I would be grateful for any help.
Kind regards
It is right, you can not instantiate a scriptable object with a position or rotation, simply because ScriptableObjects don't have components nor Transforms.
what you want to do is instantiate a prefab of your item, so you can do something like Instantiate(inventoryItems[i].itemPrefab, handSpawn.position, handSpawn.rotation);

Unity Respawning Setting Objects back active

The project is made in Unity 2D.
I am working on a unity Project where I respawn my items, after the player ran through the level. When he does not have all the emeralds he will respawn at the start of the level and I want Items to respawn for him.
So for now I am using:
void OnCollisionEnter2D (Collision2D col)
{
if (col.gameObject.CompareTag("Life"))
{
col.gameObject.SetActive(false);
}
}
The Objects are inside an empty Object for clarification. I make them the child of the empty Object "Items".
if (ManagerVariables.IsRespawning)
{
if (item!= null)
{
for (int a = 0; a < item.transform.childCount; a++)
{
item.transform.GetChild(a).gameObject.SetActive(true);
}
}
else
{
Debug.LogError("No Objects Over Class defined");
}
I already checked for the variable IsRespawning and it
is set to true when the player respawns or dies, but the
objects do not reappear.
As well I want to ask about object with multiple child objects how to do that
e.g. Enemy with FirePoint attached
The code should be working generally.
My suggestion is to check whether item has a value. Maybe item is always null and your loop never gets executed.
If item is not null I would check the child count and make sure it is larger than 0.
Regarding your question with multiple child objects, you could either disable every child individually or disable the parent, then all the children also disabled.

assign class objects instead of the actual script class to unity game objects in unity c#

I want to create a game in Unity C# in which the player will add as much as drones he needs as game objects to the game world. Therefore, I made a drone prefab and later in runtime I ask the number of drones the player wants to have (e.x. n numbers) and instantiate the prefab n times.
The script which is attached to the drone prefab is called drone_script.
Therefore, I am having a drone_script class as a general class. This class has an attribute (let's call it subscriber) which should have different unique values for each drone. So, it is created as a null reference in drone_script general class and later in runtime, I will initialize it.
During runtime, I create n (the same numbers as the drone game objects) objects from this class and assign their subscriber attribute different values.
This is how it looks:
some_class
{
for (int i = 0; i < number_of_Drones; ++i)
{
drones_script[i] = new drone_script();
\\ here I am creating n objects of my general drone_script class
drones_script[i].drone_subscriber = a unique value;
\\ here I am assigning to each of the drone objects' drone_subscriber attribute a different value.
drco = new Vector3((float)0, (float)1, (float)0);
drones[i] = Instantiate(Resources.Load("drone"), drco,
Quaternion.Euler(-90, 0, 90)) as GameObject;
\\I instatiate the drone prefab in unity game world here.
}
}
drone_script
{
public ROSBridgeSubscriber drone_subscriber;
void Start() { \\some code }
void FixedUpdate () { \\some code }
}
My problem is when the drone game objects are created in unity, the general class drone_script is attached to them and because of this their subscriber attribute is null. However, I need the drone_script[i] object to be assigned to them as their script, not the general drone_script itself. Because only then each drone game object has its corresponding subscriber attribute value from before even the start function is being called.
Am I thinking correctly?
If yes, how can I do it?
First of all, I suggest you to assign dronePrefab using editor or in Start method of "some_class" because Resources.Load("drone") might be resource consuming, since you load a drone resource "n" times.
Now your specific problem, you don't need to create new instances of "drone_script" because as you mentioned yourself, each drone that you create has his own "drone_script". So basically what we need to do is:
Instantiate drone and save his reference (as GameObject)
Get that drone's "drone_script" (using GetComponent<>(); )
Save that script reference in our array so we can use it later
Adjust some variables of that script now or later in the game
Something like that should work. In code everything should be something like this (didn't test, might be some miss types)
some_class
{
public GameObject dronePrefab;
for (int i = 0; i < number_of_Drones; ++i)
{
// Step 1.
drco = new Vector3((float)0, (float)1, (float)0);
drones[i] = Instantiate(dronePrefab, drco,
Quaternion.Euler(-90, 0, 90)) as GameObject;
// Steps 2 & 3
drones_script[i] = drones[i].GetComponent<drone_script>();
// Step 4
drones_script[i].drone_subscriber = a unique value;
}
}
EDIT:
Just to point it out: drone_script has to be attached to drone prefab

Enabling Game objects

So I've been trying to access game objects in my scene (which are disabled), to enable them. But I'm getting an error: "Object reference not set to an instance of an object"
private List<Character> characters = new List<Character>();
private List<GameObject> characterGameObjects = new List<GameObject> ();
public void loadSceneCharacters(){
if (characters != null) {
for(int i = 0; i < characters.Count; i++){
characterGameObjects.Add(GameObject.Find(characters[i].CharacterName));
characterGameObjects[i].SetActive(true);
}
}
}
You can't find disabled gameobjects.
A solution is to either reference them in inspector or find them all first when they are enabled, then disable those you don't need.
I think your characters list is empty.
If you don't Instantiate GameObjects you can fill characters list with drag and drop so you can change code like this.
public List<Character> characters = new List<Character>(); ///Thanks to public
//you can see list in Unity Editor
private List<GameObject> characterGameObjects = new List<GameObject> ();
public void loadSceneCharacters(){
if (characters != null) {
for(int i = 0; i < characters.Count; i++){
characterGameObjects.Add(characters[i])); //get and add gameobject
characterGameObjects[i].SetActive(true);
}
}
}
If you have dynamically created GameObjects you can fill the list with GameObject.Find("CharacterName");
However, i dont suggest that find every gameobject with name.Instead of that, During the Instantiate state you can add new gameObject instance to your character list.
Even if the character list would be empty this code would not throw an exception.
The problem is probably that you can not find disabled gameobject using the find methods (at least that was my experience, correct me if i am wrong guys).
What i usually do as a workaround instead of searching is to add the gameobjects via drag and drop. If this is not possible you can either, search for the gameobjects in Awake or Start, add them to your list and disable them. Or do some sort of adding when you instanciate them... Basicly you have to somehow get the reference to the gameobjects before you disable them.
Hope this helps.
Something that can help you is to create an empty object, then put all your characters inside the empty object.. then by code do something like:
foreach(Character c in MyEmptyObject.GetComponentsInChildren(Character, true))//the true in this
//line indicates that it should search for inactive objects
{
c.gameObject.SetActive(true);
}
this assuming that your characters have an script called "Character"

XNA - Collision never happens

I'm creating a game in XNA and I need a collision detection logic:
public Rectangle boundingBox = new Rectangle((int)playerShipPos.X, (int)playerShipPos.Y, frameWidth, frameHeight);
this.boundingBox = new Rectangle((int)meteorPosPub.X, (int)meteorPosPub.Y, (int)meteorTexture.Width, (int)meteorTexture.Height);
for (int i = meteorList.Count - 1; i >= 0; i--)
{
meteorGenerator meteor = new meteorGenerator(Vector2.Zero);
if (meteorList[i].meteorPosPub.Y > 664)
{
meteorList.RemoveAt(i);
if (meteor.boundingBox.Intersects(playerShip.boundingBox))
{
meteorList.RemoveAt(i);
}
}
}
So I want to achive this effect: if the player ship touches the meteor the meteor is hides and is removed from the list but nothing happens, actually.
for (int i = meteorList.Count - 1; i >= 0; i--)
{
meteorGenerator meteor = new meteorGenerator(Vector2.Zero);//you are creating new list meteors every frame, this is ridiculous
if (meteorList[i].meteorPosPub.Y > 664)
{
meteorList.RemoveAt(i);//if you are removing a position from a list, not destroying the meteor
if (meteor.boundingBox.Intersects(playerShip.boundingBox))
{
meteorList.RemoveAt(i);//you already did this, this conditional is unnecessary
}
}
}
I have no idea what it is you are doing, but this is what I would do.
1.Let the player and meteor inherit from a class with the properties a solid object would have.
Add those to a list with unique IDs based on the object type.
Every frame, check for IDs (this gives you extra control on what you want to collide with what).
Proceed to check for collisions, in case you want to remove an element, just remove it from the list and destroy it.

Categories

Resources