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 /
This question was closed Jun 28, 2018 at 10:34 AM by $$anonymous$$ for the following reason:

The question is answered, right answer was accepted

avatar image
0
Question by $$anonymous$$ · Jun 28, 2018 at 09:49 AM · c#unityeditorarraysgameobjects

What is wrong with my code? (Unity 2018, C#)

Hello, i'm more or less a beginner at Unity and C#, my code might be terrible and my techniques might be stupid, but i already know that, all i am here for is to see if someone has time to give a noobie a hand, i've been trying to figure this out for a while but nothing comes to mind. I commented the lines to make the code slightly less confusing, hope you find it understandable

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using System.Linq;
  
 public class PlaceCable : MonoBehaviour {
  
     Camera cam;
     GameObject[] childrenOfObj;
     GameObject[] anchors;
     public GameObject itemInHand;
     int childCount;
     int anchorCount = 0;
  
     void Start () {
         cam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
     }
    
  
     void Update ()
     {
         Place();
     }
  
     void Place()
     {
         if (Input.GetMouseButtonDown(1))
         {
             int anchorC = 0;
             Ray ray = cam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0.0f));
             RaycastHit hit;
             if (Physics.Raycast(ray, out hit) && !hit.collider.gameObject.CompareTag("Player") && !hit.collider.gameObject.CompareTag("MainCamera")) //if did not collide with player
             {
                 childCount = hit.collider.gameObject.transform.childCount; //how many children does the hit object have?
                 childrenOfObj = new GameObject[childCount]; //add those children to an array
  
                 for (int a = 0; a < childCount; a++)
                 {
                     childrenOfObj[a] = hit.collider.gameObject.transform.GetChild(a).gameObject;
                     if (childrenOfObj[a].gameObject.CompareTag("AnchorPoint"))
                     {
                         anchorC++;
                     }
                 } //for every anchor in those children, increase the anchor count by 1.
  
                 anchors = new GameObject[anchorC]; //initialize the anchors array with lengt of found anchors (anchor count).
  
                 for (int a = 0; a < childrenOfObj.Length; a++)
                 {
                     if (childrenOfObj[a].gameObject.CompareTag("AnchorPoint"))
                     {
                         anchors[anchorCount] = childrenOfObj[a];
                         anchorCount++;
                     }
                 } //for every child the array of children that is an anchor, add it to the array.
  
                 print("Gameobject " + hit.collider.gameObject + " has " + childrenOfObj.Length + " children" + " and has " + anchors.Length + " anchor(s)");
  
                 for (int a = 0; a < anchors.Length; a++)
                 {
                     print(anchors[a]);
                 }
  
                 GameObject itemToPlace = Instantiate(itemInHand);
  
                 if (itemToPlace != null)
                 {
                     int itemChCount = itemToPlace.gameObject.transform.childCount;
                     int anchCount = 0;
                     GameObject[] itemCh = new GameObject[itemChCount];
                     GameObject[] itemAnchors;
  
                     if (itemChCount > 0) //if the item has children
                     {
                         for (int a = 0; a < itemChCount; a++)
                         {
                             itemCh[a] = itemToPlace.gameObject.transform.GetChild(a).gameObject; //add those children to an array
                         }
  
                         for (int a = 0; a < itemChCount; a++)
                         {
                             if (itemCh[a].gameObject.CompareTag("AnchorPoint"))
                             {
                                 anchCount++; //for every anchor in that array add 1 to the count
                             }
                         }
  
                         itemAnchors = new GameObject[anchCount]; //initialize array with lenght of how many anchors there are
  
                         float[] distances = new float[anchCount]; //array of floats with lenght of how many anchors there are
  
                         for (int a = 0; a < anchCount; a++)
                         {
                             if (itemCh[a].gameObject.CompareTag("AnchorPoint"))
                             {
                                 itemAnchors[a] = itemCh[a]; //for every anchor in the array, add it to anchor array
                             }
                         }
  
                         for (int a = 0; a < anchCount; a++)
                         {
                             distances[a] = Vector3.Distance(hit.point, itemAnchors[a].transform.position); //for every anchor determine how far it is from the Raycast hit point and add it to the array
                         }
                         float smallestDistance;
  
                         smallestDistance = Mathf.Min(distances); //calculate the smallest distance in the array
  
                         GameObject ancWithSmallestDistance;
  
                         for (int a = 0; a < anchCount; a++)
                         {
                             if ((Vector3.Distance(hit.point, itemAnchors[a].transform.position) == smallestDistance))
                             {
                                 ancWithSmallestDistance = itemAnchors[a]; //find out wich anchor in the array has the smallest distance
                                 itemToPlace.transform.position = new Vector3(ancWithSmallestDistance.transform.position.x, ancWithSmallestDistance.transform.position.y, ancWithSmallestDistance.transform.position.z); //place the item on the anchor.
                                 print(ancWithSmallestDistance + " is the closest anchor wich is part of " + hit.collider.gameObject);
                                 print(itemToPlace + " is the item to place");
  
                             }
                         }
  
  
                         //print("The smallest distance is " + smallestDistance);
                         ancWithSmallestDistance = null;
                         anchCount = 0;
                         smallestDistance = 0;
                     }
                 }
                 anchors = null;
                 childrenOfObj = null;
                 childCount = 0;
                 anchorCount = 0;
             }
         }
     }
 }


Now i will explain a bit more in depth my issue and where it's happening.

I am making a game regarding machines, electricity and all that good stuff. These machines need power, and there already is a generator that takes energy from mined coal and stores it in an internal storage. What i'm trying to do here is to be able to place some cables on an object and the cables must snap to that object's "Anchor" wich is an empty GameObject with the tag "AnchorPoint".

So, player has a cable in his hand, presses right mouse button, and the cable get placed on the object he is looking at if the object has an anchor point.

alt text

The box colliders you see on the sides aren't really of use, they're just there as a reference, what matters is the empty gameobjects that they appertain to.

I don't expect you to understand my code or to find out the issue, but maybe someone is willing to give it a shot, there is no harm in trying.

test-machines.png (110.5 kB)
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

2 Replies

  • Sort: 
avatar image
1
Best Answer

Answer by M-Hanssen · Jun 28, 2018 at 10:03 AM

Sorry for the cruel answer, but was is not wrong with your code? It hurts my eyes so bad that I'm afraid to scroll up again... Please refactor your code before posting a question like this. In the process of refactoring you'll probably find the cause yourself.

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 $$anonymous$$ · Jun 28, 2018 at 10:28 AM 0
Share

As i predicted. I guess i'll rewrite it and eventually it will work. Trial and error am i right :) ?

avatar image
1

Answer by madks13 · Jun 28, 2018 at 10:22 AM

Here is the cleaned up code, a bit :

     using System.Collections;
     using System.Collections.Generic;
     using UnityEngine;
     using System.Linq;
 
     public class PlaceCable : MonoBehaviour
     {
 
         Camera cam;
         public GameObject itemInHand;
  
         void Start()
         {
             cam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
         }
 
 
         void Update()
         {
             Place();
         }
 
         void Place()
         {
             if (Input.GetMouseButtonDown(1))
             {
                 Ray ray = cam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0.0f));
                 RaycastHit hit;
                 if (Physics.Raycast(ray, out hit) && !hit.collider.gameObject.CompareTag("Player") && !hit.collider.gameObject.CompareTag("MainCamera")) //if did not collide with player
                 {
                     List<GameObject> anchors2 = GetAnchors(hit.transform);
 
                     print("Gameobject " + hit.transform + " has " + hit.transform.childCount + " children" + " and has " + anchors2.Count + " anchor(s)");
 
                     foreach (var a in anchors2)
                     {
                         print(a);
                     }
                     
                     GameObject itemToPlace = Instantiate(itemInHand);
 
                     if (itemToPlace != null)
                     {
                         List<GameObject> itemAnchors = GetAnchors(itemToPlace.transform);
                         
                         if (itemAnchors.Count > 0) //if the item has children
                         {
                             List<float> distances = new List<float>(); //array of floats with lenght of how many anchors there are
 
                             int i = 0;
                             foreach (GameObject a in itemAnchors)
                             {
                                 distances.Add(Vector3.Distance(hit.point, a.transform.position));
                             }
 
                             float smallestDistance;
 
                             smallestDistance = distances.Min(); //get the smallest distance in the array
 
                             GameObject ancWithSmallestDistance = itemAnchors[distances.IndexOf(smallestDistance)];
                             itemToPlace.transform.position = new Vector3(ancWithSmallestDistance.transform.position.x, ancWithSmallestDistance.transform.position.y, ancWithSmallestDistance.transform.position.z); //place the item on the anchor.
                             print(ancWithSmallestDistance + " is the closest anchor wich is part of " + hit.collider.gameObject);
                             print(itemToPlace + " is the item to place");
                         }
                     }
                 }
             }
         }
 
         private List<GameObject> GetAnchors(Transform item)
         {
             List<GameObject> result = new List<GameObject>();
 
             if (item != null)
             {
                 foreach (Transform child in item)
                 {
                     if (child.gameObject.CompareTag("AnchorPoint"))
                     {
                         result.Add(child.gameObject);
                     }
                 }
             }
 
             return result;
         }
     }
 

Now, can you explain what is not working properly?

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

Follow this Question

Answers Answers and Comments

520 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Double Array (Custom Editor) 1 Answer

Distribute terrain in zones 3 Answers

Is Merging GameObject Arrays Possible? 2 Answers

Unity c# indexoutofrangeexception: array index is out of range 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