C# errror "CS0116: A namespace cannot directly contain members such as fields or methods" - c#

I get an error, Assets\scripts\Skins.cs(9,12): error CS0116: A namespace cannot directly contain members such as fields or methods on the Internet they write what it means incorrectly placed brackets, but I don’t see any errors
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public GameObject choise1;
public GameObject choise2;
public GameObject choise3;
public int skin = 1;
public class Skins : MonoBehaviour {
void Choise () {
if (Input.GetMouseDown(choise1)){
choise2.SetActive (false);
}
}
}

GameObject and that int skin need to be under Skins class, like Choise
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Skins : MonoBehaviour {
public GameObject choise1;
public GameObject choise2;
public GameObject choise3;
public int skin = 1;
void Choise () {
if (Input.GetMouseDown(choise1)){
choise2.SetActive (false);
}
}
}
If you still have some problems here, because I don't know what are u trying to do with that choiseX, maybe you need to create them.
I mean, maybe u are trying to write something like this
void Choise () {
var GameObject choise1 = new GameObject();
var GameObject choise2 = new GameObject();
var GameObject choise3 = new GameObject();
int skin = 1;
if (Input.GetMouseDown(choise1)){
choise2.SetActive (false);
}
}

Related

Unity Says There is No Namespace called "Player"

I am trying make an infinite level generator that gets level parts I give to it and mix's them up to make infinite long an unique levels for me. but the problem is that When I Typed [SerializeField] private Player player; it said No namespace called "Player" which is odd because There are other code's were Player player is used and it works.Maybe I am just dumb but anyway here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelGenerator : MonoBehaviour {
private const float PLAYER_DISTANCE_SPAWN_LEVEL_PART = 200f;
[SerializeField] private Transform levelPart_Start;
[SerializeField] private List<Transform> levelPartList;
[SerializeField] private Player player;
private Vector3 lastEndPosition;
private void Awake() {
lastEndPosition = levelPart_Start.Find("EndPosition").position;
int startingSpawnLevelParts = 5;
for (int i = 0; i < startingSpawnLevelParts; i++) {
SpawnLevelPart();
}
}
private void Update() {
if (Vector3.Distance(player.GetPosition(), lastEndPosition) < PLAYER_DISTANCE_SPAWN_LEVEL_PART) {
SpawnLevelPart();
}
}
private void SpawnLevelPart() {
Transform chosenLevelPart = levelPartList[Random.Range(0, levelPartList.Count)];
Transform lastLevelPartTransform = SpawnLevelPart(chosenLevelPart, lastEndPosition);
lastEndPosition = lastLevelPartTransform.Find("EndPosition").position;
}
private Transform SpawnLevelPart(Transform levelPart, Vector3 spawnPosition) {
Transform levelPartTransform = Instantiate(levelPart, spawnPosition, Quaternion.identity);
return levelPartTransform;
}
}
I have tried to make in into a game object but then I got even more errors
No namespace called "Player"
It makes me think that the problem is in the Using.
In some parts of your code it accepts it because you are using it or it is in the same namespace.
Assuming it is called like this, try adding the using as follows
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Player; (it can change but should be like this)

Instantiate scriptableobject with random variables

I just started to work with scriptableobject, and I'm trying to Instantiate / Create Instance of a very basic scriptableobject that got 4 line of arrays.
I'm trying to Instantiate one scriptableobject that I created, that every time he's been created he will randomize his variables
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Character",menuName = "Character Creation/Player Units")]
public class CharStats : ScriptableObject
{
[SerializeField]
public string [] charName;
public string [] charDescription;
public string [] charSin;
public Sprite [] charIcon;
}
The changing I'm doing do inside the inspector for one scriptableobject, and just his inside variables will change every time I create new one. Is it possible to achieve?
Ok so I manage to create something might be not the right way, but after pressing a key ( for now testing) its Instantiate my scriptableobjectwith a random Icon I put on for now. Ill add the 3 scripts, bad names coz it's for testing only, (testing - its script that sitting on empty gameobject with reference to my scriptableobject, testing 2 - its script that sitting on a prefab that I Instantiate with the scriptableobject)
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
public class testing2 : MonoBehaviour
{
//public ScriptableObject person;
public CharStats charSats;
public Sprite sprite2;
private SpriteRenderer spriteRender;
private void Start()
{
spriteRender = GetComponent<SpriteRenderer>();
GetRandomSprite();
}
public Sprite GetRandomSprite()
{
int randomIndex = Random.Range(0, charSats.charIcon.Length);
Debug.Log(charSats.charIcon[randomIndex]);
if (sprite2 == null)
{
sprite2 = charSats.charIcon[randomIndex];
spriteRender.sprite = sprite2;
}
return charSats.charIcon[randomIndex];
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
public class Testing : MonoBehaviour
{
public GameObject Player;
private void Update()
{
SpawnPlayer();
}
public void SpawnPlayer()
{
if (Input.GetKeyDown(KeyCode.A))
{
GameObject spawnPalyer = Instantiate(Player, new Vector3(Random.Range(-10,10), Random.Range(-10, 10)), Quaternion.identity) as GameObject;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Character",menuName = "Character Creation/Player Units")]
public class CharStats : ScriptableObject
{
[SerializeField]
public string [] charName;
public string [] charDescription;
public string [] charSin;
public Sprite [] charIcon;
}

Setting levels in a quiz game

This is my first post to Stack Overflow so please be gentle. I have followed the video tutorial at https://learn.unity.com/tutorial/live-session-quiz-game-1 and have been able to successfully modify it so that images are shown as questions instead of text. The next step for me is to divide my game into Levels. I have added the appropriate extra 'Rounds' in the DataController object referred to at the end of video 3 start of video 4 so that it now looks like this:
So here is the question, if I want to add a set of buttons to a Levels page, and then add an OnClick event to each, how do I point that OnClick event specifically to the set of questions for each Level? I think I need to point the onClick at a script passing a variable that is the level number, but not sure how to do it and so far searches of StackOverflow and YouTube haven't really helped?
EDIT
I have done the following and I seem to be a lot closer:
Created a new scene called LevelSelect and added the buttons I need for the levels to it;
I created a script in the scene called LevelSelectController and to this I added the button registration script provided by Lothan;
I registered the buttons as suggested via drag and drop;
I created a Function within the LevelSelectController script called StartGame, this had one line:
Debug.Log("Button pressed is: Level " + (setLevel + 1));
I ran the script and the buttons responded as expected;
All I am struggling with now his how to get the button press to pass the integer for the level number to the allRoundData variable in the DataController. The code for each script looks like this:
DataController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class DataController : MonoBehaviour
{
public RoundData[] allRoundData;
public int currentLevel;
// Start is called before the first frame update
void Start()
{
DontDestroyOnLoad (gameObject);
SceneManager.LoadScene ("MenuScreen");
}
public RoundData GetCurrentRoundData()
{
return allRoundData [currentLevel];
}
// Update is called once per frame
void Update()
{
}
}
LevelSelectController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LevelSelectController : MonoBehaviour
{
public List<Button> buttonsList = new List<Button>();
private DataController dataController;
public void StartGame(int setLevel)
{
Debug.Log("Button pressed is: Level " + (setLevel + 1));
}
}
GameController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameController : MonoBehaviour
{
public Text questionText;
public Image questionImage;
public SimpleObjectPool answerButtonObjectPool;
public Transform answerButtonParent;
private DataController dataController;
private RoundData currentRoundData;
private QuestionData[] questionPool;
private bool isRoundactive;
private float timeRemaining;
private int questionIndex;
private int playerScore;
private List<GameObject> answerButtonGameObjects = new List<GameObject> ();
// Start is called before the first frame update
void Start()
{
dataController = FindObjectOfType<DataController> ();
currentRoundData = dataController.GetCurrentRoundData ();
questionPool = currentRoundData.questions;
timeRemaining = currentRoundData.timeLimitInSeconds;
playerScore = 0;
questionIndex = 0;
ShowQuestion ();
isRoundactive = true;
}
private void ShowQuestion()
{
RemoveAnswerButtons ();
QuestionData questionData = questionPool[questionIndex];
questionText.text = questionData.questionText;
questionImage.transform.gameObject.SetActive(true);
questionImage.sprite = questionData.questionImage;
for (int i = 0; i < questionData.answers.Length; i++)
{
GameObject answerButtonGameObject = answerButtonObjectPool.GetObject();
answerButtonGameObjects.Add(answerButtonGameObject);
answerButtonGameObject.transform.SetParent(answerButtonParent);
AnswerButton answerButton = answerButtonGameObject.GetComponent<AnswerButton>();
answerButton.Setup(questionData.answers[i]);
}
}
private void RemoveAnswerButtons()
{
while (answerButtonGameObjects.Count > 0)
{
answerButtonObjectPool.ReturnObject(answerButtonGameObjects[0]);
answerButtonGameObjects.RemoveAt(0);
}
}
// Update is called once per frame
void Update()
{
}
}
How do I now pass the value of setLevel in LevelSelectController to currentLevel in the DataController script?
Welcome to StackOverflow!
You can do it using different ways, but one could be:
First register all the buttons:
List<Button> buttonsList = new List<Button>();
Then assign to each button the behaviour to do when onClick (registering the listener) passing the info of the corresponding DataController:
for(int i = 0; i < buttonsList.Count; i++)
{
buttonsList[i].onClick.AddListener(() => SetLevel(DataController.allRoundData[i]))
}
There are some leaps of faith in this current answer cause I don't know about your code, but if you have doubts, comment and I'll update the answer ^^
With a little extra research I was able to use a static variable along with Lothan's suggestion to get to the solution. Here is the modified code:
LevelSelectController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LevelSelectController : MonoBehaviour
{
static public int currentLevel
public List<Button> buttonsList = new List<Button>();
void Start()
{
for(int i = 0; i < buttonsList.Count; i++)
{
int levelNum = i;
buttonsList[i].onClick.AddListener(() => {currentLevel = levelNum;});
}
}
public void StartLevel()
{
SceneManager.LoadScene ("Game");
}
}
And only one edit needed in the Start() of GameController.cs, from
currentRoundData = dataController.GetCurrentRoundData ();
to:
currentRoundData = dataController.GetCurrentRoundData (LevelSelectController.currentLevel);

How could i fix an error (cs0120) in unity?

In unity, I'm trying to make a press of a button increase the speed of the player. However, each time I run it. It gives me:
Error CS0120: An object reference is required for the non-static
field, method, or property 'PlayerController.speed'
I've already tried changing order of the code, so what could I do?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Upgrader1 : MonoBehaviour
{
void Start()
{
GameObject Player = GameObject.Find("Player");
PlayerController PlayerController = Player.GetComponent<PlayerController>();
}
public void Upgrade1()
{
PlayerController.speed++;
}
}
public class Upgrader1 : MonoBehaviour
{
PlayerController PlayerController; //It should be member variable
void Start()
{
GameObject Player = GameObject.Find("Player");
PlayerController = Player.GetComponent<PlayerController>();
}
public void Upgrade1()
{
PlayerController.speed++;
}
}
it's always a good thing to use proper naming conventions.
PlayerController _PlayerController;
void Start() {
GameObject Player = GameObject.Find("Player");
_PlayerController = Player.GetComponent<PlayerController>();
}
public void UpgradeSpeed() // I changed the name according to its functionality
{
_PlayerController.speed++;
}
With this, you won't put PlayerController class reference again by mistake.

Instantiating a list of gameobjects in Unity C#

How can I instantiate a list of GameObject in Unity3D using c#?
I fill the list with prefabs manually in inspector window.
Below is the code I've written in Deck.cs, but I get "Object reference is not set to an instance of an object". If you have a solution with an array, that will be appreciated as well.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
namespace Assets
{
class Deck:MonoBehaviour
{
public List<GameObject> deck;
public void Fill()
{
GameObject c1 = Instantiate(deck[0]);
GameObject c2 = Instantiate(deck[1]);
GameObject c3 = Instantiate(deck[2]);
GameObject c4 = Instantiate(deck[3]);
GameObject c5 = Instantiate(deck[4]);
GameObject c6 = Instantiate(deck[5]);
}
}
}
I also tried doing it with an array and I get 'The object you want to instantiate is null'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
namespace Assets
{
class Deck:MonoBehaviour
{
public GameObject card1;
public GameObject card2;
public GameObject card3;
public GameObject card4;
public GameObject card5;
public GameObject card6;
public GameObject[] deck;
public void Start ()
{
deck = new GameObject[5];
GameObject c1 = Instantiate(card1) as GameObject;
GameObject c2 = Instantiate(card2) as GameObject;
GameObject c3 = Instantiate(card3) as GameObject;
GameObject c4 = Instantiate(card4) as GameObject;
GameObject c5 = Instantiate(card5) as GameObject;
GameObject c6 = Instantiate(card6) as GameObject;
}
}
}
Well considering your comments and that the first script your provided works perfectly without any error (as it should: there's no reason it should return an error), I feel like you are very new to Unity.
Therefore I'd recommend you to look to the Unity tutorials before anything else (they are quite well made and will help you understand the basics of the engine). You can find the Roll-a-ball tutorial here.
About your question:
1- In the first script, the Fill() method isn't called anywhere, you have to do something like this:
private void Start()
{
Fill();
}
2- This Start() method comes from the MonoBehaviour parent class (as well as the Update() method which is called every frame) and is called once at the beginning of the scene. Look to this chart to understand how unity flow is made.
3- Using a List<GameObject> or a GameObject[] all depends on your situation: if the size of the collection is going to change, go for a list. Otherwise array is advised.
4- Considering your script my guess is it should look like this:
namespace Assets
{
class Deck : MonoBehaviour
{
[SerializeField]
private GameObject[] deck;
private GameObject[] instanciatedObjects;
private void Start()
{
Fill();
}
public void Fill()
{
instanciatedObjects = new GameObject[deck.Length];
for (int i = 0; i < deck.Lenght; i++)
{
instanciatedObjects[i] = Instanciate(deck[i]) as GameObject;
}
}
}
}
You can of course still use lists if needed :)
EDIT:
If you want to use a list you simply have to:
change private GameObject[] instanciatedObjects; to private List<GameObject> instanciatedObjects;
replace instanciatedObjects = new GameObject[deck.Length]; by instanciatedObjects = new List<GameObject>();
replace instanciatedObjects[i] = Instanciated(deck[i]) as GameObject; by instanciateObjects.Add(Instanciated(deck[i]) as GameObject);
Hope this helps,
Use foreach to loop over your List with prefabs, like this:
public List<GameObject> Deck = new List<GameObject>(); // im assuming Deck is your list with prefabs?
public List<GameObject> CreatedCards = new List<GameObject>();
void Start()
{
Fill();
}
public void Fill()
{
foreach(GameObject _go in Deck)
{
GameObject _newCard = (GameObject)Instantiate(_go);
CreatedCards.Add(_newCard);
}
}
Also it's a good habit to name your lists with capital letter.

Categories