How to get child object [duplicate] - unity3d

This question already has answers here:
How to find child of a GameObject or the script attached to child GameObject via script
(4 answers)
Closed 5 years ago.
I try to access FirstPersonCharacter from my script by using FPSController.
I pass FPSController to my script. Now I try to intialize FirstPersonCharacter which is a child of FPSController.
I pass FPSController to the script, now I try to use FPSController to initialize FirstPersonCharacter, because I try to avoid too many public variables, especially if it is not necessary.
public GameObject FPSController;
private GameObject FirstPersonCharacter;
I need help at the initialisation part:
void Start()
{
FirstPersonCharacter = ???
}
I tried it like this:
void Start()
{
FirstPersonCharacter = FPSController.transform.GetChild(0);
}
But I get Cannot implicitly convert type "UnityEngine.Transform" to "UnityEngine.GameObject"

It works like this:
FirstPersonCharacter = FPSController.transform.GetChild(0).transform.gameObject;

Related

Unity: How do I pass as a parameter, a nested list initialized in its own class, to a method?

I will try to keep this to the point. I have created a nested list of GameObjects with:
[System.Serializable] public class TabSlots { public List<GameObject> tabslots; } [System.Serializable] public class Tablature { public List<TabSlots> tablature; } public Tablature allSlots = new Tablature();
This worked quite well, and I was able to drop the appropriate GameObject(s)
into their respective slots in the Inspector, which hierarchy looked like this:
AllSlots (This is the root of the nested list)
Tablature (12 elements)
Tabslots (3 elements)
I was able to successfully access the components of each GameObject in Tabslots. In the following example, I move an object in deck[0] to the position of allSlots.tablature[0].tabslots[0]. (deck is simply a one-level list of GameObjects)
deck[0].transform.position = Vector2.MoveTowards(deck[0].transform.position, allSlots.tablature[0].tabslots[0].transform.position, 70f * Time.deltaTime);
My QUESTION: How do I send the nested list created by: public Tablature allSlots = new Tablature(); to an IEnumerator method?
I have tried every possible combination I can think of for the call ( ??? represents the undiscovered code).
StartCoroutine(MyTest(deck, ??? ));
And also tried everything I could think of with the parameter list in the IEnumertor method ( ??? represents the undiscovered code).
IEnumerator MyTest((List<GameObject> list1, ??? ))
Can someone help me fill in the ??? blanks?
Thank you forward.
I have tried all the combinations of reference that I could think of.
You can just pass the type that you created:
...
StartCoroutine(MyTest(deck, allSlots));
}
private IEnumerator MyTest(List<GameObject> deck, Tablature tablature)
{
return null;
}

NullReferenceException problem in Unity when object is not null [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
I am trying to troubleshoot the following piece of code which causes a NullReferenceException. Essentially when an object is created, I'm trying to have it register with my game manager class. This is the component for my object:
void Start()
{
Debug.Log("Registering");
if (gameObject != null)
{
GameMngr.Instance.RegisterAttraction(gameObject);
}
else
{
Debug.Log("Gameobject null");
}
}
In my game manager I have the following:
public void RegisterAttraction(GameObject newAttraction)
{
if (newAttraction != null)
{
Debug.Log("Attempting to register gameObject");
attractionLastID++;
sceneAttractions.Add(attractionLastID, newAttraction);
Debug.Log("Registered");
}
else
{
Debug.Log("unable to register: null provided");
}
}
My console output is as following:
Registering
Attempting to register gameObject
NullRefereceException
The fact that my code displays the attempting to register gameObject lines leads me to believe that my newAttraction variable is not null. Why do I get the error ?
Thank for the help
Where's attractionLastId defined by chance? Is it being initialized? Since you're doing a null check inside of your Start function already, try refactoring your RegisterAttraction function to look something like:
public void RegisterAttraction(GameObject newAttraction)
{
Debug.Log("Attempting to register gameObject");
attractionLastID++;
sceneAttractions.Add(attractionLastID, newAttraction);
Debug.Log("Registered");
}
I highly recommend setting a breakpoint on the beginning curly of RegisterAttraction. Take it step by step and hover over each variable to see which one is null.

Serialization of a list of custom objects in unity

While trying to make a script for building assets, I ran into an issue with unity's serialization. I have a class in which I store some arbitrary information, which is then stored in an array in a MonoBehaviour on a prefab. I cannot for the life of me get the array to save however, as when I make the object into a prefab it loses the list's values. I have tried using [System.Serializable] and ScriptableObject, but both seem to pose their own new issues.
For instance, using ScriptableObject would mean having to save the data objects as assets, which would become way too much since these objects can get to hundreds in number.
Am I making a mistake in my understanding of unity's serialization? Is there a way to get this working without the ScriptableObject approach of saving every ArbitraryInfo object in an asset?
Data object:
[System.Serializable]
public class ArbitraryInfo{
public int intValue;
public Vector3 vectorValue;
}
OR
public class ArbitraryInfo : ScriptableObject {
public int intValue;
public Vector3 vectorValue;
void OnEnable() {
hideflags = HideFlags.HideAndDontSave;
}
}
Behaviour:
public class MyBuilder : MonoBehaviour {
public ArbitraryInfo[] infoArray;
}
Editor:
[CustomEditor(typeof(MyBuilder))]
public class MyBuilderEditor : Editor {
private SerializedProperty infoArrayProperty;
void OnLoad() {
infoArrayProperty = serializedObject.FindProperty("infoArray");
}
void OnInspectorGUI() {
serializedObject.Update();
for (var i = 0; i < infoArrayProperty.arraySize; i++) {
if (i > 0) EditorGUILayout.Space();
var info = infoArrayProperty.GetArrayElementAtIndex(i).objectReferenceValue as ArbitraryInfo;
EditorGUILayout.LabelField("Info " + i, EditorStyles.boldLabel);
info.intValue = EditorGUILayout.IntField(info.intValue);
info.vectorValue = EditorGUILayout.Vector3Field(info.vectorValue);
}
serializedObject.ApplyModifiedProperties();
}
}
EDIT 1, Thank you derHugo
I changed my code to incorporate the changes. Now there are errors for ArbitraryInfo not being a supported pptr value.
Secondly, ArbitraryInfo no longer being a ScriptableObject poses the question of how to initialize it. An empty object can be added to infoArrayProperty through infoArrayProperty.arraySize++, but this new empty object seems to be null in my case. This might be due to the pptr issue mentioned above.
EDIT 2
The issue I was having was caused by another piece of code where I tried to check if infoArrayProperty.objectReferenceValue == null. I changed this to another check that did the same thing and everything worked!
No, no ScriptableObject needed.
But note that GetArrayElementAtIndex(i) returns a SerializedProperty. You can not simply parse it to your target class.
so instead of
var info = infoArrayProperty.GetArrayElementAtIndex(i).objectReferenceValue as ArbitraryInfo;
and
info.intValue = EditorGUILayout.IntField(info.intValue);
info.vectorValue = EditorGUILayout.Vector3Field(info.vectorValue);
you have to get the info's SerializedPropertys by using FindPropertyRelative:
var info = infoArrayProperty.GetArrayElementAtIndex(i);
var intValue = info.FindPropertyRelative("intValue");
var vectorValue = info.FindPropertyRelative("vectorValue");
than you can/should use PropertyFields
EditorGUILayout.PropertyField(intValue);
EditorGUILayout.PropertyField(vectorValue);
allways try to avoid using direct setters and use those SerializedProperties instead! This provides you with Undo/Redo functionality and marking the changed Behaviour/Scene as unsaved automatically. Otherwise you would have to tak care of that manually (... don't ^^).

CS0589 unexpected syntax error in Unity3d

I am totally new to Unity and at the moment i am taking a course at Udemy. In course we have to create a game like flappy bird. We have created an object which has to move from right to left. Then we made a script which is as follow:
using UnityEngine;
public class Object : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Translate(Vector3.left * (20 * Time.deltaTime));
}
}
The next thing we have to do connect this script to the object but than it goes wrong. It won't let me do that because there is an error in it. The error should be on line of the public class, but the teacher has the same code and it works for him. Is there something i am missing. This is very frustrating.
Thanks in advance.
According to
CS0589
The compiler found unexpected syntax.
I guess this have to do with this line.
public class Object : MonoBehaviour
Object is a default type in C#. Try chaning the name of the class.

Check if spawn is empty

I have two spawn spots where a player will show up upon connection.
I need that, when one of the players connects on one of the spots, any other player will always spawn at the other spot.
Here's some visual in case it helps: https://goo.gl/Y0ohZC
Here is the code I'm using:
using UnityEngine;
using System.Collections;
public class SpawnSpot : MonoBehaviour {
public int teamId=0;
public GameObject[] Spots; //Drag the spots in here (In the editor)
bool[] OccupiedSpawnSpots;
//Using Photon Networking
void OnJoinedRoom()
{
//Request the recent OccupiedSpawnSpots List
PhotonView.RPC("RequestList", PhotonTargets.MasterClient, PhotonNetwork.player);
}
//In "RequestList" the MasterClient sends his List of the SpawnSpots
//by calling "ReceiveList"
[RPC]
void RequestList(PhotonPlayer player)
{
PhotonView.RPC("ReceiveList", PhotonTargets.All, player, OccupiedSpawnSpots);
}
[RPC]
void ReceiveList(PhotonPlayer Sender, bool[] ListOfMasterClient)
{
OccupiedSpawnSpots = ListOfMasterClient;
//Get the free one
if (OccupiedSpawnSpots[0] == false)
{
//Spawn player at 0
if (Sender == PhotonNetwork.player)
PhotonNetwork.Instantiate("PlayerController", Spots[0].transform.position);
OccupiedSpawnSpots[0] = true;
}
else
{
//Spawn player at 1
if (Sender == PhotonNetwork.player)
PhotonNetwork.Instantiate("PlayerController", Spots[1].transform.position);
OccupiedSpawnSpots[1] = true;
}
}
The errors given are:
Assets/Scripts/SpawnSpot.cs(14,28): error CS0120: An object reference
is required to access non-static member `PhotonView.RPC(string,
PhotonPlayer, params object[])'
Assets/Scripts/SpawnSpot.cs(22,28): error CS0120: An object reference
is required to access non-static member `PhotonView.RPC(string,
PhotonPlayer, params object[])'
Assets/Scripts/SpawnSpot.cs(36,47): error CS1501: No overload for
method Instantiate' takes3' arguments
Assets/Scripts/SpawnSpot.cs(43,47): error CS1501: No overload for
method Instantiate' takes3' arguments
Thanks in advance, IC
It appears that you are trying to call an instance function using a static reference. instead of doing PhotonView.RPC("RequestList", PhotonTargets.MasterClient, PhotonNetwork.player);
you need to create a reference to an PhatorView object, and then call the RPC function on it.
public PhotonView photonView;
void OnJoinedRoom()
{
if(photonView == null)
{
photonView = GetComponent<PhotonView>();
}
//Request the recent OccupiedSpawnSpots List
PhotonView.RPC("RequestList", PhotonTargets.MasterClient, PhotonNetwork.player);
}
you should have a PhotonView object on the same GameObject that this script is on, or assign a reference to a PhotonView in the editor.
That should fix your problems, but I think you should look into compiler errors and how to to fix them. In Unity3D if you double click the error in the console it will take you to the line that isn't compiling. It also tends to give you a pretty good hint as to why it isn't compiling.
your error was this
"Assets/Scripts/SpawnSpot.cs(14,28): error CS0120: An object reference is required to access non-static member `PhotonView.RPC(string, PhotonPlayer, params object[])'"
which means that you need an object in order to call this function.
The third and fourth errors are because you are calling Instantiate with only 2 arguments, but it takes at least 4. Include the rotation of the GameObject you're trying to instantiate, and a group number:
PhotonNetwork.Instantiate("PlayerController", Spots[0].transform.position, Quaternion.identity, 0);
Note that you may not want the identity quaternion, so you may need to change this. Also I'm not familiar with PhotonNetwork so 0 may not be an advisable group.