New answers tagged

0

First you'll need to extend your input binding map to handle things that aren't key codes, something like this: public enum BindingType { Unset, Keyboard, MouseButton, MouseScroll } [System.Serializable] public struct InputBinding { public BindingType type; public KeyCode key; public int mouseButton; public Vector2 ...


1

This is the way: inputField.onEndEdit.Invoke(inputField.text); I'm trying to do it because the InputField component does not allow you to have a button to finish the editing of the text, so I'm adding it. That's why I want to call the event when the button is pressed, which means that the edit is finished.


1

Delegates can be used to achieve what you're doing but the code here will most likely not 'just work' with what you already have. In addition, I've had to make several assumptions about how things work / what you have described (see assumptions at the end). Cards Given your description, I imagine the interface your cards use to look something like this: ...


1

As the comments have indicated, delegates may be your saviour, but let me add a little context and maybe a few extra pointers. delegates are nice because you can form a subscriber system whereby the player can be subscribed to the card with some functions X that executes the desired actions on the card. however delegates may not be the perfect solution as ...


2

As is usually the case, this is happening because you told Unity that's what you wanted to happen. This block says: void Start() { GunAnimations = GetComponent<Animator>(); "As soon as this script starts, please throw away whatever value I'd put in the GunAnimations variable in the inspector. Instead, I want you to use the Animator component ...


0

you are just lopping the through characters in first sentence as the index never gets updated. just wrap your code with new for or foreach loop. this is just my psudo code for your problem. string[] sentences; float TypeSpeed; ienumerator displayText() { for(int i=0; i<sentences.length;i++) { for(int j=0;j<sentences[i].length;j++) { ...


0

This is a straightforward application of Mathf.Clamp(value, min, max). Ordinarily I'd recommend caution calculating new orientations from Euler angles, but for camera orientation it's typically safe enough. You might want to pull back slightly from 90, say 80 degrees, so you don't hit nasty behaviour right at the poles. // Correct for deltaTime so your ...


0

You can use if condition such as: float v = verticalSpeed * Input.GetAxis("Mouse Y"); if (v > 100) then //100 your limit {v= 50} else {v=30} or you can use math.sign function which gives you +1,0,-1 if the result for your case v > 0 it returns +1 if it is zero than 0 if it is negative then it is -1 you can limit your camera by ...


1

you can use GetBool("State Name") function to check sprint any where. but right Animator design is always the key to freedom on changing you character behaviour. this is my example code: bool sprint= anim.getBool("sprint"); if(sprint) return; //you shooting logic here


2

I guess a possible solution is to have a bool that handles if the player is allowed to shoot. public class Shooting : MonoBehaviour { /// .... public bool AllowedToShoot = true; void Update() { if (AllowedToShoot == false) return; // if not allowed to shoot, don't run the code bellow // your code } } public class ...


5

The recipe is simple: Divide by your desired interval, so now each multiple of the interval maps to an integer. Round to the nearest integer. Multiply by your interval to bring it back to the original scale. Here's an example: static float RoundTo(float value, float multipleOf) { return Mathf.Round(value/multipleOf) * multipleOf; }


1

Should it not be calling Start() BEFORE any other function call? No, that's not the promise the engine makes to you. Consulting the docs: Start is called on the frame when a script is enabled just before any of the Update methods are called the first time. It promises you that it will call ScriptA.Start() before it, the engine, calls ScriptA.Update() or ...


0

What happens here is basically this: When you click on a planet for the first time, isSelected is set to true. Then you click away, but since you don't check whether other planets were selected, isSelected remains true. The next time you try to select it, it first detects, that it is indeed the current active planet (based on the variable) and deactivates ...


0

Can you use DontDestroyOnLoad for your player ? Maybe you could use an external script that assign what you want in your player script depending of what you want. Ex: GameObject player; void Start() { player = GameObject.Find("player"); if(//insert condition) { player.GetComponent<playerManager>().gender = "man"; } }


3

Sinse you are new to C#, make sure you read up on properties if you haven't already done so. Because over-simplified, they are basically special methods that look like a variable to the end user. Due to them actually being methods, the C# compiler can't know for sure what you are doing to retrieve the value. So that warning might be over-zealous yes, but ...


2

I'm unable to reproduce this problem. In my tests with this code, the first time I click the button I go to the "Intro" scene. Any subsequent run of the game, I go to the scene named in the SceneName variable. So, this is likely due to incorrect setup in your project/scenes/inspector. Things you can try: Verify that both scenes have been added to ...


2

A raycast is like shining a laser pointer in your scene, to see what the laser hits. It takes a starting point and a direction as input (together, they make a "ray"). The physics engine takes this point and sweeps it along that direction. As it goes, it searches through all the physics colliders in your scene to check whether the point hits any of them ...


1

You can use WaitWhile to define a condition for the coroutine's yield. Something like this could work, with a button configured to update the value of buttonPressed accordingly. public class IntroToForest : MonoBehaviour { public bool buttonPressed; void Start() { StartCoroutine(LoadScene()); } IEnumerator LoadScene() { ...


2

Rather than running this as a coroutine, ticking every frame waiting to see if the button is pressed, I'd just store the AsyncOperation and let the button give it a kick when the player finally presses it. public class ScenePreloader : MonoBehaviour { public string sceneName; AsyncOperation preload; void Start() { preload = ...


1

Just use a boolean flag. public class IntroToForest : MonoBehaviour { public bool buttonPressed = false; void Start() { StartCoroutine(LoadScene("Forest Map")); } IEnumerator LoadScene(string scene) { AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(scene); asyncOperation.allowSceneActivation = ...


0

It looks like you're sorting using a boolean value as your sort key. That means many items in your list will compare as equal (true == true and false == false) When two items are equal, an unstable sort like List.Sort(Comparison<T>) is allowed to put them in any order. And it's allowed to make different decisions from one run to another (this ...


0

I presume the flow for setting the key is to click the box of the action and then pressing the key the player wants to bind to it. You can also listen to mouse clicks in that time and use the first action that is performed.


0

There is no need to do that when unity offers sprites and spline based animation for you to do your animation it would be a right approach for you to follow the already suggested way to animate rather than thinking of new methods to do stuffs you could probably do those things when you go higher level and ask these doubts to unity folks themselves.:D


0

I think this code should do what you want, its quite self-explanatory but if you have any question just don't hesitate to ask. private float _lastFillAmountChangeTime; private float _fillAmount; private float _timer; public float FillAmount { get { return _fillAmount;} set { // register the change if input value != current value ...


1

Ah, linear algebra. Few things that probably no one told you, but are pretty essential to understand matrices and rotations (i hope i don't mix the names, never learned maths in english). Each point in space has a position, dependent on the basis you defined (you know, the perpendicular arrows starting at [0, 0]) Each column of the rotation matrix defines ...


2

Accessing by index is a little fragile, if the structure of your prefab were ever to change. As your object is a prefab, you might consider adding fields to your ConveyorBelt script for the start and end position objects instead, like so: public class ConveyorBelt : MonoBehaviour { [SerializeField] private Transform targetStart; [SerializeField] ...


1

Arrays in C# can't be appended-onto. What you might want instead is a List, which behaves a lot like an array, but you can add items to it: // Declaration of member variable - you can initialize it at the same time. public List<Transform> children = new List<Transform>(); ... // Populate the list's contents in a method like Start(). foreach(...


0

Every game object can have only one Transform compinent. You are trying to get multiple Transform components from one transform. Instead you should loop through parent's children. If monsterOne is your Transform of the parent. Example: for(int i = 0; i < monsterOne.childCount; i++) { monsterOne.GetChild(i); //This is the transform of each child in ...


0

Whelp, I feel silly now. I thought I kept stumbling over this before but the answer is in the documentation example. This is how I am doing it: using System.Collections; using System.Collections.Generic; using UnityEngine; public class ConveyorBelt : MonoBehaviour { public bool isMoving = true; public float speed = 0.1f; private float offset = ...


1

Ok, so your task is actually to project point onto line, defined by two points. Code: XY d = a + XY.Project (c - a, b - a); XY is a 2-dimensional vector with these methods defined: /// projection of vector v onto vector w public static XY Project (XY v, XY w) => XY.Dot (v, w) / XY.Dot (w, w) * w; /// dot product of vectors a and b public static float ...


1

Remember, video games, and the computers that run them, are just machines. They do only what you tell them to, in the order you tell them to do it. Right now, you only tell the machine "make the game's fullscreen state match this UI toggle" in the callback method after the player clicks it: public void SetFullscreen (bool isFullscreen) { Screen....


0

Think about how a foreach works: foreach (var number in Enumerable.Range(1, 1000000)) { if (number > 10) break; } The control over the iteration is on the caller - if you stop the iteration (here with break), that's it. The yield keyword is a simple way to make an enumerable in C#. The name hints at this - yield return yields control back to the ...


13

The reason is the keyword yield which has a specific meaning in C#. On encountering the words yield return a function in C# returns, as one would expect. Using yield to define an iterator removes the need for an explicit extra class [...] When a yield return statement is reached in the iterator method, expression is returned, and the current ...


0

Global functions: Find one object with tag: GameObject.FindWithTag Find all objects with tag: GameObject.FindGameObjectsWithTag Now, if you want to find an object with a tag that is also a child of a specific object you can use the following function: Transform FindWithTag(Transform root, string tag) { foreach (Transform t in root....


1

ratchet freak's answer is an excellent explanation of the differences between using Thread.Delay() and coroutines in Unity. To address your second question, I suspect what you're looking for is WaitForSeconds. From the documentation: public class WaitForSecondsExample : MonoBehaviour { void Start() { StartCoroutine(Example()); } ...


1

A simple explanation: under the hood Unity is iterating over a collection (of YieldInstructions or nulls or whatever you yield return) using the IEnumerator that your function returns. Since you use the yield keyword, your method is an iterator. It's not the Unity thing, it's a C# language feature. How does it work? It is lazy and doesn't generate all the ...


1

Another answer mentions that you are stopping co-routines when "Fire1" is up - this is completely correct, insofar as why the coroutine does not continue instantiating GameObjects after the first press of "Fire1". In your case however this code will not become 'stuck' in an infinite loop, which is what it looks like you're looking for an answer to - i.e. ...


3

Coroutines are a strange beast. Yield return causes the method to suspend execution until it is later stepped. Behind the scenes, it might look something like this: class FireContinuouslyData { int state; bool shouldBreak; } object FireContinuously(FireContinuouslyData data) { switch (data.state) { case 0: goto State_0; }...


8

When the fire button is lifted, the second if statement is entered, and StopAllCoroutines is run. This means that the Coroutine that the while loop is running in is ended, thus there is no more infinite loop. The coroutine is like a container for the code to execute in. I can recommend the Unity Manual and the Unity Scripting API to get a better grasp on ...


0

The problem with delay() as traditionally implemented (stopping the thread until it can continue again) means exactly that, it stops the thread and it cannot do anything else. One underappreciated feature of unity (and in fact most game engines and gui frameworks) is that most of the main logic is executed on a single thread. This makes programming a lot ...


0

Your code shown here doesn't actually depend on GameObjects - they're just serving as an expensive way for you to store a set of positions. So you could get something equivalent as follows, just using transformation matrices instead: // You can assign the default Unity cube here so you have a template mesh to stamp-out. public Mesh cubeMesh; public static ...


4

I've never done this, and I'm not familiar with Unity, but here's how I'd do it. You could use the PlayerPrefs to implement that feature. When your player hits "Play", start first by checking if they have a preference saved. If they have, skip the intro, if not, save the preference and play the intro. if ( PlayerPrefs.HasKey("HasSeenIntro") { // skip ...


0

This works fine as well: material.SetColor("_BaseColor", color);


0

you can re-create the sprite and set the size of the texture 2d being assigned to the pic. //assign size to match ui pic this.profilePic.sprite = Sprite.Create(tex, new Rect(0, 0, 128, 128), new Vector2(0, 0));


0

When you want to prevent your players from reverse-engineering your game, you are fighting a battle against windmills. You can make them jump through hoops, but you can not prevent it. And if anyone ever finds your level details and secret items through the regular ingame methods, they will just create a wiki and share it with the whole community. You can't ...


25

You can use a using alias directive to give System.Random a new name as well: using Rng = System.Random;


30

You could specify the namespace explicitly: System.Random random = new System.Random(seed); random.Next();


0

From a security standpoint, as you note, they're basically equivalent (which is to say not secure at all). So it doesn't particular matter on that front. Generally speaking I'd suggest you keep data (constant or otherwise) distinct from code, because then you don't have to go through the process of rebuilding the game (and in some cases repackaging it also) ...


0

Your design does seem massively overcomplicated. I find it useful to think about the divisions of responsibilities. You say that You want items that may have skills associated with them that activate when the item is used. Items in your inventory can be stacked and some items may be consumed when used. These are two different things, and I believe that ...


1

Did you try something like this? childToTarget = targetPosition - child.position; childToTarget.y = 0; parent.position+= childToTarget;


Top 50 recent answers are included