Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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
5
Question by Nolan Encarnacion · Apr 07, 2011 at 11:06 PM · raycastarrayselecting

C# adding items to an already created Array

Hello Unity Community,

I am having a really hard time trying to create a piece of code that would add objects that I would select into an array. I was doing some research and it said that I would only be able to do the array.Add or array.Push in java. Which sucks because our project is in C#, is there any alternative that I could possible look into for this problem Thanks, Nolan Encarnacion

using UnityEngine; using System.Collections;

public class SelectionManager : MonoBehaviour { public RaycastHit hit; public Ray ray; public GameObject[] selection; // Use this for initialization

 // Update is called once per frame
 void Update () 
 {
     if ( Input.GetMouseButtonDown(0) )
     {
       ray = Camera.main.ScreenPointToRay (Input.mousePosition);
       if (Physics.Raycast (ray, out hit, 100))
       {
         addtoArray(hit.collider.gameObject);
         Debug.Log(selection);
          //Debug.Log(hit.collider.gameObject.name);
       }
    }

 }
 void addtoArray(gameObject obj)
 {
     selection.Add(obj);
 }

}

Comment
Add comment
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

4 Replies

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

Answer by Mike 3 · Apr 07, 2011 at 11:21 PM

You generally want to use List for this kind of thing

Add this to the top of the file:

using System.Collections.Generic;

then this instead of your array:

List<GameObject> selection;

Add should work fine then

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 Nolan Encarnacion · Apr 09, 2011 at 02:55 PM 0
Share

Thank you for your response it was very helpful!

avatar image
12
Best Answer

Answer by Peter G · Apr 07, 2011 at 11:23 PM

No, you have to recreate the array with its new member. You may as well make it a generic method:

using System.Collections.Generic;

public static class Extensions {

 public static T[] AddItemToArray &lt;T&gt; (this T[] original, T itemToAdd) {

      T[] finalArray = new T[ original.Length + 1 ];
      for(int i = 0; i &lt; original.Length; i ++ ) {
           finalArray[i] = original[i];
      }

      finalArray[finalArray.Length - 1] = itemToAdd;

      return finalArray;
 }

}

So as you can see, it isn't very easy to resize arrays.

Or, as Mike said right before I posted, you should probably just use a List. It will handle this for you.

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 Nolan Encarnacion · Apr 09, 2011 at 02:56 PM 0
Share

yeah I think I'm just going to use a list. $$anonymous$$UCH easier haha! Thank you though for your response. It is much appreciated.

avatar image
3

Answer by V-Jankaitis · Jun 27, 2018 at 02:06 PM

 T[] AddtoArray<T>(T[] Org, T New_Value)
         {
             T[] New = new T[Org.Length + 1]; 
             Org.CopyTo(New, 0);
             New[Org.Length] = New_Value;
             return New;
         }
Comment
Add comment · Show 3 · 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 ativtrade · Aug 17, 2021 at 06:15 PM 0
Share

Did you mean:

New[New.Length] = New_Value;

in line 5?

avatar image Bunny83 ativtrade · Aug 17, 2021 at 08:03 PM 0
Share

No, he didn't. The max valid index is always "Length-1". Since the new length is actually the old length +1 he can simply use the old length as index into the new array.

Example

 // length of array: 4
 // index  0   1   2   3
 // value  A   B   C   D
 
 // new array length: 4+1 == 5
 // index  0   1   2   3   4
 // value  A   B   C   D  New
avatar image ativtrade Bunny83 · Aug 17, 2021 at 08:56 PM 0
Share

Hmm.. effectively recycling Org.Length instead of writing New.Length-1 I think I get it. Thanks for the explanation.

avatar image
0

Answer by mx_official · Aug 11, 2020 at 10:17 AM

If anyone needed the same script but for models with multiple materials, here you go.

edit: Made fadePerSecond serialized for others who will be using the script in their own way.

 using System.Collections.Generic;
 using UnityEngine;
 
 public class FadeAlpha : MonoBehaviour
 {
     [SerializeField] private float fadePerSecond = 0;
     
     [SerializeField] private List<Material> materials = new List<Material>();
 
     [SerializeField] private bool moreThanOneMat = false;
 
  
     void Start()
     {
         // Locating Materials
         if (GetComponent<MeshRenderer>().materials.Length > 1)
         {
             moreThanOneMat = true;
 
             foreach (Material m in GetComponent<MeshRenderer>().materials)
             {
                 materials.Add(m);
             }
         }
     }
 
     void Update() 
     {
         if (moreThanOneMat == true)
         {
             DropAlphaForAll();
         }
         else
         {
             var material = GetComponent<MeshRenderer>().material;
             var color = material.color;
 
             if (color.a > 0)
             {
                 material.color = new Color(color.r, color.g, color.b, color.a - (fadePerSecond * Time.deltaTime));
             }
             if (color.a < 0)
             {
                 material.color = new Color(color.r, color.g, color.b, 0);
             }
         }
     }
 
     void DropAlphaForAll()
     {
         if (GetComponent<MeshRenderer>().materials.Length > 1)
         {
             foreach (Material mats in materials)
             {
                 if (mats.color.a > 0)
                 {
                     mats.color = new Color(mats.color.r, mats.color.g, mats.color.b, mats.color.a - (fadePerSecond * Time.deltaTime));
                 }
                 if (mats.color.a < 0)
                 {
                     mats.color = new Color(mats.color.r, mats.color.g, mats.color.b, 0);
                 }
             }
         }
     }
 }
 
Comment
Add comment · 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

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Array index is out of range and Raycast question 0 Answers

Raycast cycle problem? 0 Answers

Return a List of Gameobjects at the mouse position 0 Answers

Hover Effect with more rays as turbines? 1 Answer

Select an Enemy C# 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