Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by ThisMayBeMadness · May 28, 2011 at 07:58 PM · gameobjectcomponentallextract

How do I extract all the components of a gameobject and place them in to a new gameobject?

Hey there, I'm trying to extract ALL the components of a gameobject and then place them in a new gameobject at a later date after the original gameobject has been destroyed.

In effect I'm trying to clone the gameobject without the original object being there.

In C#.

It's for an inventory script. The user approaches the object then presses 'E' to 'collect' it. The object is detected with capsuletracing. I know this part works.

This is what I've got so far:

First, the struct, which I create outside of the main class:

public struct InventoryItems
{
    public string itemName;
    public Component[] itemComponents;
}

Then start:

void Start()
{
    realInventory = new InventoryItems[10];
    inventoryCollectionPrompt=0;
}

Then inside update:

if(Input.GetKeyUp(KeyCode.E))
{
    realInventory[0].itemName = hit_fwd.transform.gameObject.name;
    realInventory[0].itemComponents = hit_fwd.transform.gameObject.GetComponents(typeof(Component));
    Destroy(hit_fwd.transform.gameObject);
}

I know it gets the right number of components (in this case 5) through Debug.Log(realInventory.itemComponents.Length).

Then I try to 'restore' the gameobject by pressing 'F':

    if(realInventory[0].itemName!=null)
    {
        if(Input.GetKeyUp(KeyCode.F))
        {
            restoreItem();
        }

This is the restoreItem procedure:

void restoreItem()
{
    int i=0;
    GameObject Cake = new GameObject(realInventory[0].itemName);
    Cake.transform.position = transform.position;
    while(i < realInventory[0].itemComponents.Length)
    {
        Cake = Cake.AddComponent
 
  ("Test");
        i++;
    }
}

 

For some reason, AddComponent only accepts a string rather than component. Same with GetComponents. Where I have used it is simply guesswork, as I have never used AddComponent before as per the Unity script reference which is remarkably non-descriptive in this case.

I have tried to be as detailed as possible in my explanation of what I am trying to do. If I have left something vital out, please ask for it.

I would also like to request that answers are more than code correction/replacement and actually include explanations as to why those corrections/replacements are there, as it helps to further my learning.

Thanks in advance.

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Dreamblur · May 28, 2011 at 08:48 PM 0
Share

As far as I know, and I may be wrong since I've never used AddComponent before either, AddComponent adds a component with all of its inherent values set to default. The reason it requires a string is because it adds a component with the name of the string value you passed. It only needs that name to add the component because all other values of the component will be set to their default values anyway. Logically, it makes sense, but since I haven't tested it myself, I can't definitively prove it. Anyway, try the following line of code:

Cake.AddComponent<(typeof(realInventory[0].itemComponents[i]))>();

(Your code is trying to replace the value of the game object Cake with the value of the component you are adding.)

I can't assure you that it will work though, since like I said, I've never used AddComponent before. If it doesn't work, try casting it as a string. But remember that if it does work, the values in your component will most prolly have been reset to their default values.

Do the values of the components in your item change in the first place? If they don't, you can just make a prefab out of your item and instantiate that ins$$anonymous$$d.

As an aside, you might want to use a for loop ins$$anonymous$$d of a while loop in your restoreItem method.

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Wolfram · May 28, 2011 at 10:39 PM

Instead of destroying a GameObject and recreating it identically some place else, just disable it temporarily, for example with gameObject.SetActiveRecursively(false).

If you want to create a clone of a GameObject, just use newObject=Instantiate(originalObject). You cannot copy or move individual Components this way, it's all or nothing.

If you want to move an object to a different point in your scene hierarchy, just reparent it with myObject.transform.parent=newParent.transform

You cannot copy individual Components and keep their settings.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ThisMayBeMadness · May 29, 2011 at 09:09 AM 1
Share

This is great, it works perfectly. I understand your answer. I cannot copy the gameobject, but I can disable it (so for all intents and purposes it is removed from the game world). Then I can move it and then reactivate it as I choose, whilst at the same time making it appear to have been stored as an inventory item using various other means. Thanks! :D

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Disable/Enable Script or Add/Remove? 1 Answer

Disabling GameObject doesn't disable components 0 Answers

Is it OK to use public accessers for unique gameobjects (C#) ? 3 Answers

Find a Component/GameObject Using an Interface Reference 2 Answers

How to get all scripts attached to a gameojbect? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges