I’m fairly new to c# and unity and I don’t know what this error means, i’m trying to make the floor tilt like in super monkey ball, I know how it all works but I copied and pasted it so to not make mistakes and to save time.
This is the code, please help
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Floor_Control : MonoBehaviour{}
{
public float speed;
public float max;
void FixedUpdate()
{
//Player Input
float step = speed * Time.deltaTime;
float tiltX = -Input.GetAxis("Horizontal") + Input.GetAxis("Vertical");
float tiltZ = Input.GetAxis("Horizontal") + Input.GetAxis("Vertical");
GetComponent<Rigidbody>().rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(max * tiltZ, 0, max * tiltX), step);
}
}
asked Jan 15, 2020 at 19:44
3
Remove the braces after MonoBehaviour «{}». You also don’t have a namespace declaration which may also generate that error message:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace TestProgram
{
public class Floor_Control : MonoBehaviour
{
public float speed;
public float max;
void FixedUpdate()
{
//Player Input
float step = speed * Time.deltaTime;
float tiltX = -Input.GetAxis("Horizontal") + Input.GetAxis("Vertical");
float tiltZ = Input.GetAxis("Horizontal") + Input.GetAxis("Vertical");
GetComponent<Rigidbody>().rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(max * tiltZ, 0, max * tiltX), step);
}
}
}
answered Jan 15, 2020 at 20:02
Mark McWhirterMark McWhirter
1,1683 gold badges11 silver badges28 bronze badges
1
В чем заключается проблема ?
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class GameController : MonoBehaviour
{
struct CubePos(0, 1, 0);
public float cubeChangePlaceSpeed = 0.5f;
public Transform cubeToPlace
}
private List<Vector3> allCubesPosition = new List<Vector3>
{
new Vector3(0, 0, 0),
new Vector3(1, 0, 0),
new Vector3(-1, 0, 0),
new Vector3(0, 1, 0),
new Vector3(0, 0, 0),
new Vector3(-1, 0, -1),
new Vector3(1, 0, 1),
new Vector3(0, 0, -1),
new Vector3(1, 0, -1),
}
private void Start()
{
StartCoroutine(ShowCubePlace());
}
IEnumerator ShowCubePlace()
{
while(true)
{
SpawnPosition();
yield return new WaitForSeconds(cubeChangePlaceSpwwd)
}
}
private void SpawnPosition()
{
List<Vector3> position = new List<Vector3>();
if (IsPositionEmpty(new Vector3(nowCube.x + 1, nowCube.y, nowCube.z)))
position.Add(new Vector3(nowCube.x + 1, nowCube.y, nowCube.z));
if (IsPositionEmpty(new Vector3(nowCube.x - 1, nowCube.y, nowCube.z)))
position.Add(new Vector3(nowCube.x - 1, nowCube.y, nowCube.z));
if (IsPositionEmpty(new Vector3(nowCube.x, nowCube.y + 1, nowCube.z)))
position.Add(new Vector3(nowCube.x, nowCube.y + 1, nowCube.z));
if (IsPositionEmpty(new Vector3(nowCube.x, nowCube.y - 1, nowCube.z)))
position.Add(new Vector3(nowCube.x, nowCube.y - 1, nowCube.z));
if (IsPositionEmpty(new Vector3(nowCube.x, nowCube.y, nowCube.z + 1)))
position.Add(new Vector3(nowCube.x, nowCube.y, nowCube.z + 1));
if (IsPositionEmpty(new Vector3(nowCube.x, nowCube.y, nowCube.z - 1)))
position.Add(new Vector3(nowCube.x, nowCube.y, nowCube.z - 1));
cubeToPlace.position = position[UnityEngineRandom.Range(0, positions.Count)]
}
private bool IsPositionEmpty(Vector3 targetPos)
{
if (targetPos.y == 0)
return false;
foreach(Vector3 pos in allCubesPositions)
{
if (pos.x == targetPos.x && pos.y == targetPos.y && pos.z == targetPos.z)
return false;
}
return true;
}
public int x, y, z;
{
public CubePos(int x, int z, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
public Vector3 getVector()
{
return new Vector3(x, y, z);
}
public void setVector(Vector3 pos)
{
x = Convert.ToInt32(pos.x);
y = Convert.ToInt32(pos.y);
z = Convert.ToInt32(pos.z);
}
}
I keep getting error CS1022 (twice) with this code. I am new to C# coding, so I’m not sure what’s going on or how to fix it. Can someone please help?
Error 1: AssetsSodaCan.cs(29,1): error CS1022: Type or namespace definition, or end-of-file expected
Error 2: AssetsSodaCan.cs(31,1): error CS1022: Type or namespace definition, or end-of-file expected
Edit: Issue has been fixed
In C#, all executable code is contained in methods: only variable and class definitions can be outside — and variables need to be within a class.
So your if
code needs to be inside a method to be effective:
private float myFloat = 0.0f; public void myMethod(float myParameter) { if (myParameter == 666.0f) { ... } }
And although #if
exists, it doesn’t get executed when your code is running — it’s a directive to the compiler to include or exclude code when you build the EXE file, not included in the EXE for later execution.
If you think of it like a car, when your buy a new car you select the options you want on it: black paint, 20″ rims, and Cruise control for you! That provides directives to the car manufacturer when they build it:
#if (paint == Black) PaintIt(Black) #elseif (paint = Red) PaintIt(Red) #else PaintIt(White);
That «fixes the options» on the car, they don’t change from that point on and when delivered to you it will be black, sit higher, and have an extra stick on the steering column. You can use the cruise control at any time while you drive it, but unless you selected it with #if
when you bought the car, it doesn’t exist and you can’t use it.
#if
in C# code, does the same thing: selects what code is comp0iled and stored into the EXE you run later. if
is used to make decisions when the EXE file is running and you are playing the game, reading data from a DB, or shatever you app is trying to do.
In C#, all executable code is contained in methods: only variable and class definitions can be outside — and variables need to be within a class.
So your if
code needs to be inside a method to be effective:
private float myFloat = 0.0f; public void myMethod(float myParameter) { if (myParameter == 666.0f) { ... } }
And although #if
exists, it doesn’t get executed when your code is running — it’s a directive to the compiler to include or exclude code when you build the EXE file, not included in the EXE for later execution.
If you think of it like a car, when your buy a new car you select the options you want on it: black paint, 20″ rims, and Cruise control for you! That provides directives to the car manufacturer when they build it:
#if (paint == Black) PaintIt(Black) #elseif (paint = Red) PaintIt(Red) #else PaintIt(White);
That «fixes the options» on the car, they don’t change from that point on and when delivered to you it will be black, sit higher, and have an extra stick on the steering column. You can use the cruise control at any time while you drive it, but unless you selected it with #if
when you bought the car, it doesn’t exist and you can’t use it.
#if
in C# code, does the same thing: selects what code is comp0iled and stored into the EXE you run later. if
is used to make decisions when the EXE file is running and you are playing the game, reading data from a DB, or shatever you app is trying to do.
В чем заключается проблема ?
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class GameController : MonoBehaviour
{
struct CubePos(0, 1, 0);
public float cubeChangePlaceSpeed = 0.5f;
public Transform cubeToPlace
}
private List<Vector3> allCubesPosition = new List<Vector3>
{
new Vector3(0, 0, 0),
new Vector3(1, 0, 0),
new Vector3(-1, 0, 0),
new Vector3(0, 1, 0),
new Vector3(0, 0, 0),
new Vector3(-1, 0, -1),
new Vector3(1, 0, 1),
new Vector3(0, 0, -1),
new Vector3(1, 0, -1),
}
private void Start()
{
StartCoroutine(ShowCubePlace());
}
IEnumerator ShowCubePlace()
{
while(true)
{
SpawnPosition();
yield return new WaitForSeconds(cubeChangePlaceSpwwd)
}
}
private void SpawnPosition()
{
List<Vector3> position = new List<Vector3>();
if (IsPositionEmpty(new Vector3(nowCube.x + 1, nowCube.y, nowCube.z)))
position.Add(new Vector3(nowCube.x + 1, nowCube.y, nowCube.z));
if (IsPositionEmpty(new Vector3(nowCube.x - 1, nowCube.y, nowCube.z)))
position.Add(new Vector3(nowCube.x - 1, nowCube.y, nowCube.z));
if (IsPositionEmpty(new Vector3(nowCube.x, nowCube.y + 1, nowCube.z)))
position.Add(new Vector3(nowCube.x, nowCube.y + 1, nowCube.z));
if (IsPositionEmpty(new Vector3(nowCube.x, nowCube.y - 1, nowCube.z)))
position.Add(new Vector3(nowCube.x, nowCube.y - 1, nowCube.z));
if (IsPositionEmpty(new Vector3(nowCube.x, nowCube.y, nowCube.z + 1)))
position.Add(new Vector3(nowCube.x, nowCube.y, nowCube.z + 1));
if (IsPositionEmpty(new Vector3(nowCube.x, nowCube.y, nowCube.z - 1)))
position.Add(new Vector3(nowCube.x, nowCube.y, nowCube.z - 1));
cubeToPlace.position = position[UnityEngineRandom.Range(0, positions.Count)]
}
private bool IsPositionEmpty(Vector3 targetPos)
{
if (targetPos.y == 0)
return false;
foreach(Vector3 pos in allCubesPositions)
{
if (pos.x == targetPos.x && pos.y == targetPos.y && pos.z == targetPos.z)
return false;
}
return true;
}
public int x, y, z;
{
public CubePos(int x, int z, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
public Vector3 getVector()
{
return new Vector3(x, y, z);
}
public void setVector(Vector3 pos)
{
x = Convert.ToInt32(pos.x);
y = Convert.ToInt32(pos.y);
z = Convert.ToInt32(pos.z);
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Net; using Random = UnityEngine.Random; [RequireComponent(typeof(Rigidbody))] public class CarController : MonoBehaviour { public bool rightTurn, leftTurn, moveFromUp; public float speed = 15f, force =50f; private Rigidbody carRb; private float rotateMultRight = 6f, rotateMultLeft = 4.5f, originRotationY; private Camera mainCam; public LayerMask carsLayer; private bool isMovingFast; [NonSerialized] public bool carPassed; public GameObject turnLeftSignal, turnRightSignal, explosion, exhaust; [NonSerialized] public static bool isLose; [NonSerialized] public static int countCars; public AudioClip crash; public AudioClip[] accelerator; private void Start() { mainCam = Camera.main; carRb = GetComponent<Rigidbody>(); originRotationY = transform.eulerAngles.y; if (rightTurn) StartCoroutine(TurnSignals(turnRightSignal)); else if (leftTurn) StartCoroutine(TurnSignals(turnLeftSignal)); } IEnumerator TurnSignals(GameObject turnSignal) { while (!carPassed) { turnSignal.SetActive(!turnSignal.activeSelf); yield return new WaitForSeconds(0.5f); } } private void Update() { #if UNITY_EDITOR Ray ray = mainCam.ScreenPointToRay(Input.mousePosition); #else if (Input.touchCount == 0) return; Ray ray = mainCam.ScreenPointToRay(Input.GetTouch(0).position); #endif RaycastHit hit; if (Physics.Raycast(ray, out hit, maxDistance: 100f, carsLayer)) { string carName = hit.transform.gameObject.name; #if UNITY_EDITOR if (Input.GetMouseButtonDown(0) && !isMovingFast && gameObject.name == carName) { #else if (Input.GetTouch(0).phase == TouchPhase.Began && !isMovingFast && gameObject.name == carName) #endif { GameObject vfx = Instantiate(exhaust, new Vector3(transform.position.x, transform.position.y + 1.5f, transform.position.z), Quaternion.Euler(90, 0, 0)) as GameObject; Destroy(vfx, 2f); speed *= 2.5f; isMovingFast = true; } if (PlayerPrefs.GetString("music") != "No") { GetComponent<AudioSource>().clip = accelerator[Random.Range(0, accelerator.Length)]; GetComponent<AudioSource>().Play(); } } } } private void FixedUpdate() { carRb.MovePosition(transform.position - transform.forward * speed * Time.fixedDeltaTime); } private void OnCollisionEnter(Collision other) { if (other.gameObject.CompareTag("Car")) { isLose = true; speed = 0f; other.gameObject.GetComponent<CarController>().speed = 0f; GameObject vfx = Instantiate(explosion, transform.position, Quaternion.identity) as GameObject; Destroy(vfx, 4f); if (isMovingFast) force *= 1.2f; carRb.AddRelativeForce(Vector3.back * force); if (PlayerPrefs.GetString("music") != "No") { GetComponent<AudioSource>().clip = crash; GetComponent<AudioSource>().Play(); } } } private void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Car") && other.GetComponent<CarController>().carPassed) other.GetComponent<CarController>().speed = speed; } private void OnTriggerStay(Collider other) { if (isLose) return; if (other.transform.CompareTag("TurnBlock Right") && rightTurn) { RotateCar(rotateMultRight); } else if(other.transform.CompareTag("TurnBlock Left") && leftTurn) { RotateCar(rotateMultLeft, -1); } } private void OnTriggerExit(Collider other) { if (other.transform.CompareTag("Trigger Pass")) { if (carPassed) return; carPassed = true; Collider[] colliders = GetComponents<BoxCollider>(); foreach (Collider col in colliders) col.enabled = true; countCars++; } if (other.transform.CompareTag("TurnBlock Right") && rightTurn) carRb.rotation = Quaternion.Euler(0, originRotationY + 90f, 0); else if (other.transform.CompareTag("TurnBlock Left") && leftTurn) carRb.rotation = Quaternion.Euler(0, originRotationY - 90f, 0); else if (other.transform.CompareTag("DestroyCars")) Destroy(gameObject); } private void RotateCar(float speedRotate, int dir = 1) { if (isLose) return; if (dir == -1 && transform.localRotation.eulerAngles.y < originRotationY - 90f) return; if (dir == -1 && moveFromUp && transform.localRotation.eulerAngles.y > 250f && dir == -1 && transform.localRotation.eulerAngles.y < 270f) return; float rotateSpeed = speed * speedRotate * dir; Quaternion deltaRotation = Quaternion.Euler(new Vector3(0, rotateSpeed* Time.fixedDeltaTime, 0) ); carRb.MoveRotation(carRb.rotation * deltaRotation); } } 2)using System; using UnityEngine; using GoogleMobileAds.Api; public class AdssManager : MonoBehaviour { #if UNITY_EDITOR string adUnitId = "ca-app-pub-7216743424948383/4317969368"; #elif UNITY_ANDROID string adUnitId = "unexpected_platform"; #elif UNITY_IPHONE string adUnitId = "unexpected_platform"; #else string adUnitId = "unexpected_platform"; #endif private InterstitialAd interstitial; private int nowLoses; private void Start() { DontDestroyOnLoad(gameObject); DestroyAndStartNew(true); } private void Update() { if (interstitial.IsLoaded() && GameController.countLoses % 3 == 0 && GameController.countLoses != 0 && GameController.countLoses != nowLoses) { nowLoses = GameController.countLoses; interstitial.Show(); } } public void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args) { DestroyAndStartNew(); } public void HandleOnAdClosed(object sender, EventArgs args) { DestroyAndStartNew(); } public void HandleOnAdLeavingApplication(object sender, EventArgs args) { DestroyAndStartNew(); } void DestroyAndStartNew(bool isFirst = false) { if (!isFirst) interstitial.Destroy(); interstitial = new InterstitialAd(adUnitId); // Called when an ad request failed to load. this.interstitial.OnAdFailedToLoad += HandleOnAdFailedToLoad; // Called when the ad is closed. this.interstitial.OnAdClosed += HandleOnAdClosed; // Called when the ad click caused the user to leave the application. //this.interstitial.OnAdLeavingApplication += HandleOnAdLeavingApplication; AdRequest request = new AdRequest.Builder().Build(); // Load the interstitial with the request. this.interstitial.LoadAd(request); } } 3)using System; using UnityEngine; using UnityEngine.Purchasing; public class IAPPManager : MonoBehaviour, IStoreListener { public static IAPPManager instance; private static IStoreController m_StoreController; private static IExtensionProvider m_StoreExtensionProvider; private const string REMOVE_ADS = "remove_ads"; private const string OPEN_CITY = "open_city"; private const string OPEN_MEGAPOLIS = "open_megapolis"; public void InitializePurchasing() { if (IsInitialized()) return; var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance()); builder.AddProduct(REMOVE_ADS, ProductType.NonConsumable); builder.AddProduct(OPEN_CITY, ProductType.NonConsumable); builder.AddProduct(OPEN_MEGAPOLIS, ProductType.NonConsumable); UnityPurchasing.Initialize(this, builder); } private bool IsInitialized() { return m_StoreController != null && m_StoreExtensionProvider != null; } public void BuyNoAds() { BuyProductID(REMOVE_ADS); } public void BuyCityMap() { BuyProductID(OPEN_CITY); } public void BuyMegapolisMap() { BuyProductID(OPEN_MEGAPOLIS); } public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args) { if (String.Equals(args.purchasedProduct.definition.id, REMOVE_ADS, StringComparison.Ordinal)) { // Товар был куплен успешно, можно его отдать пользователю PlayerPrefs.SetString("NoAds", "yes"); Destroy(GameObject.Find("Ad")); //Destroy(GameObject.Find("noadsbutton")); } else if (String.Equals(args.purchasedProduct.definition.id, OPEN_CITY, StringComparison.Ordinal)) { PlayerPrefs.SetInt("Coins", PlayerPrefs.GetInt("Coins") +1000); GameObject shopCntrl = GameObject.Find("ShopController"); shopCntrl.GetComponent<BuyCoinMap>().BuyNewMap(1000); } else if (String.Equals(args.purchasedProduct.definition.id, OPEN_MEGAPOLIS, StringComparison.Ordinal)) { PlayerPrefs.SetInt("Coins", PlayerPrefs.GetInt("Coins") + 5000); GameObject shopCntrl = GameObject.Find("ShopController"); shopCntrl.GetComponent<BuyCoinMap>().BuyNewMap(5000); } else { // Неуспешный платеж } return PurchaseProcessingResult.Complete; } private void Awake() { TestSingleton(); } void Start() { if (m_StoreController == null) InitializePurchasing(); } private void TestSingleton() { if (instance != null) { Destroy(gameObject); return; } instance = this; DontDestroyOnLoad(gameObject); } void BuyProductID(string productId) { if (IsInitialized()) { Product product = m_StoreController.products.WithID(productId); if (product != null && product.availableToPurchase) { Debug.Log(string.Format("Purchasing product asychronously: '{0}'", product.definition.id)); m_StoreController.InitiatePurchase(product); } else Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase"); } else { Debug.Log("BuyProductID FAIL. Not initialized."); } } public void RestorePurchases() { if (!IsInitialized()) { Debug.Log("RestorePurchases FAIL. Not initialized."); return; } if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.OSXPlayer) { Debug.Log("RestorePurchases started ..."); var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>(); apple.RestoreTransactions((result) => { Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore."); }); } else { Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform); } } public void OnInitialized(IStoreController controller, IExtensionProvider extensions) { Debug.Log("OnInitialized: PASS"); m_StoreController = controller; m_StoreExtensionProvider = extensions; } public void OnInitializeFailed(InitializationFailureReason error) { Debug.Log("OnInitializeFailed InitializationFailureReason:" + error); } public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason) { Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason)); } } |