#💻┃code-beginner
1 messages · Page 685 of 1
sounds like you've got two copies of the same script in the scene probably?
put this
Debug.Log($" {name} [SPACE] pressed during game!", this);
click both logs and see if they take you to 1 object / script
Dont code at 2am kids
I literally moved the script from an empty game object to different object but didnt delete the empty one
tired **
thanks @rich adder and @wintry quarry
im gonna head to bed before i break anything else ❤️

making a basic jump script, how do i make it only work when touching the ground? here's my code
public Rigidbody2D rb;
private void Start()
{
jumpAction = InputSystem.actions.FindAction("Jump");
}
private void Update()
{
if (jumpAction.WasPressedThisFrame()) { rb.linearVelocityY = jumpPower; }
}
For starters, check that you're on the ground before allowing them to jump . . .
use a raycast and check if it hits the ground
yeah that's what i meant how do i do that
You can find a solution on YouTube or Google by searching: ground check Unity . . .
ok thanks
There are tons of resources for that. Just search using the same question you asked us . . .
Does anybody know any good ways to check when there are no active instances of a prefab in a scene? I'm making an asteroids clone to learn the ropes of Unity and I'm trying to detect when all the asteroids are destroyed so I can instantiate another round.
You could probably use object pooling with the asteroids and be able to tell how many asteroids you've got with it's collection/array implementation. I wouldn't recommend searching the hierarchy for objects unless you really have no other choice. If they share a single parent, you could probably use this to get the number of children https://docs.unity3d.com/ScriptReference/Transform-childCount.html
Huh, I didn't think about that. I'll try that out thanks 👍
you don't need to check the transform child count tbh. if you go the object pool route, unitys object pool has properties you can use to get the number of objects active/inactive or both https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Pool.ObjectPool_1.html
Or if you dont go the pooling route, you need to store these objects in a list. Instantiate returns the spawned object. either remove it from the list when the objects are destroyed or just check if the list elements are null every so often.
getting the child count forces you to have these asteroids as children of a specific object which is a bit fragile and not needed
Alright thanks, I'll try that too
hey guys, so basically I am trying to see if a player has pressed a button while inside of a trigger using the if (Input.GetButtonDown) function but whenever I run it it errors with this error ArgumentException: Input Button Interact is not setup. To change the input settings use: Edit -> Project Settings... -> Input Manager UnityEngine.Internal.InputUnsafeUtility.GetButtonDown (System.String buttonName) (at <44a762dafa6b4e0ca8423d645d61ba11>:0) UnityEngine.Input.GetButtonDown (System.String buttonName) (at <44a762dafa6b4e0ca8423d645d61ba11>:0)
but how can this be whenever it is
It says Input Manager, not Input System Package
the Input class is not the new input system
it isnt? ummm stupid question but how would I change that
The input system docs are pinned to #🖱️┃input-system
so its not the updated system?
because I am using all the correct packages
sorry for ping forgot to turn it off
It's a completely different API you have to use, you write completely different code
because I have to use a controller?
like a player movement controller
uhh input controller
idk what its called
the new input system is just a completely separate thing from the old input system. the input methods are still the same they're just handled and coded differently
i'd reccomend looking at docs or finding a tutorial online if you don't understand how it works.
and lemme guess the new one is better?
i personally think so, I don't know the specifics of it. but if you plan to add controller support then it definitely makes the process a lot easier.
Hi, is there a way to log an exception with the clickable stack trace and a custom message?
I tried this:
Debug.LogException(new(
$"(Audio Manager) Failed to get or create source for '{audioItem.Name}'", e));
However, that logs the inner exception first, and the exception message later.
That's quite annoying and makes no sense.
Is it possible to somehow work around this?
Please @ me and thanks in advance!
Hi I'm trying to have a game button that when I press it it loads the game so basically here's the code that i have and it doesn't work pls help
Error Message from Unity : Assets\MainMenu.cs(6,21): error CS0246: The type or namespace name 'MonoBehavior' could not be found (are you missing a using directive or an assembly reference?)
Code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Play : MonoBehavior
{
// Update is called once per frame
void Update()
{
}
// une fonction de "public" qui genere la scene choisi
public void PlayGameScene ()
{
SceneManager.LoadScene("Quarry");
}
}
Unless things have changed, behaviour should be with a u
thank you so much!!!!!!😭
it works let's gooooooooooo
dosn't load the scene though 😂 I'm going to work on that now
Did you save the scene as Quarry in build settings?
it's that right?
found the problem it's on me i forgot to put the working code in unity my bad
it was set on no function😅
bump
Is this how u would make a SceneLoad without having the script on any gameObject?
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void InitOnLoad()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
private static void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
TexturesLoaded.Clear();
Debug.Log("TexturesLoaded cleared on scene: " + scene.name);
}
im guessing i can just have it like this too?
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void InitOnLoad()
{
TexturesLoaded.Clear();
}
actually im just going to make a gameobject and just have it a reference since that would be easier for my life
hy guys could somebody pls tell me how to show a menu in a game by pressing a button.
As of right now I have a little game project that works and the menu pannel that lunch at the start of the game from wich I can lunch it or exit from it.
How can I go to that pannel by pressing "M", while being in the game, I only understood that it's by the event system but I don't know how to do it.
Pls help
Here's my code for now :
function Update()
{
if (Input.GetKeyDown("m"))
{
SceneManager.LoadScene("MainMenu");
}
}
here's my error warning
using UnityEngine;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour {
void Update(){
if(Input.GetKeyDown(KeyCode.M)){
SceneManager.LoadScene("MainMenu");
}
}
}
You need to go learn the basics of C#, because this is not C#
Also !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hey all,
Could anyone help me out with a little Logic & Maths please, my head is spinning a little. 😕
Basically trying to generate a black and white image (using red atm cause of another issue) at runtime with a couple of 'bands' of white on black based on input values between 0 and 90 for use as a mask elsewhere.
https://hastebin.com/share/jagopilofo.java
This is my current code. I'm certain there's a maths error in the ConvertLatitudeRange as my results don't seem to make sense (ie, I believe minMaxLatitude.y should be 614.4f.)
(Current Vector2 input is 30,60)
width is 1 (doesn't need to be bigger than that)
height is 1024
equator is height/2 (=512)
Couple of images for reference
1, input settings (Ignore Terrain layers section in Inspector, all that is disabled for now
2, current results
3, Highly detailed engineering schematic of what I'm trying to achieve.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
colliders are starting to piss me off.
i use a grid collider on my grid map, i get stuck in nothing, same for enemies, cuz its "uneven" fir some stupid reason.
i use a composite collider, some raycast fail because they are cast inside the ground, bu dont detect it cuz composite collider is like not filled, additionally, it doesnt work well with astar pathfinding graphs.
wth am i supposed to do?
What is a "grid collider"?
You mean a tilemap collider?
Make sure your physics shapes are right
Best practices for modular architecture question
I have a ball and a zone. I would like the ball to destroy once it touches the zone.
My "Death" code goes on the ball. The zone however, should hold what it does independently of that right?
Should the zone, once collided with, tell the ball to run the Death code? This way if I have another zone that, lets say increases the amount of points you get or something, I could have the zone do both by having them be separate scriptable objects attached to the zone.
Otherwise, if I have the zone just say "hey, you hit me, I have x tags) and the ball read those tags then fire off the appropriate methods, the ball would end up containing a ton of code for each possible interaction with a zone. Even if the method doesn't affect the ball (Similar to the points example.)
Am I thinking correctly about this? I'm a bit mixed up cause I'm under the impression that the zone shouldn't talk to the ball, but this might be from previously working in godot where you "call up, signal down", or is this the same thing?
Yes I think it makes sense for the death zone to tell the ball to die
Maybe the zone could have an interface with some method like Interract() that does some different logic depending on what type of zone is it.
That way the ball script doesnt care about what type of zone it is, it just automatically calls Interract() if it enters any kind of zone
hi so I've got this code to be able to go back to my menu if the character is inside the trigger zone, however for some reason when I press "m", it doesn't do anything and I am stuck in the current scene, how can I change scene by pressing "m", what is wrong in my code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MoveScene_OnKeyPress : MonoBehaviour
{
[SerializeField] private string MainMenu;
[SerializeField] private GameObject uiElement;
private void OntriggerStay(Collider other)
{
if(other.CompareTag("Player"))
{
uiElement.SetActive(true);
if(Input.GetKeyDown(KeyCode.M))
{
SceneManager.LoadScene(MainMenu);
}
}
}
private void OnTriggerExit(Collider other)
{
if(other.CompareTag("Player"))
{
uiElement.SetActive(false);
}
}
}
@sharp bloom If I have 5 types of zones though, wouldn't the ball need code for what each zone types does?
two things:
- make sure the code is running (hint: it isn't)
- GetKeyDown is only true for the first frame that the key is pressed which is not necessarily going to be a physics update frame. so you need to rework your logic a bit so you are checking for input in Update instead
wait hold on I thought the code would be running if I put it in an object in Unity could you explain that to me pls?
what calls OntriggerStay
how, it's a private method and isn't a unity message
so if i put my collider object name it should work?
oh
yea maybe thats a bit much
is the UI appearing though ?
which part isn't working
so when I load the game and I go to my trigger it doesn't show the text to change scene
and even if i press m it still doesn't change scene
forget the keypress, is the UI appearing
have you fixed the logic issue i pointed out
no
no cause I didn't quite get it
do you have at least 1 rigidbody or your tag is not set
ah yes, let's ignore advice about fixing an issue instead of asking clarifying questions. good choice 👍
it's in rigid body but it's not set
just didn't understand it that's why i asked about the first part before going to the second
clarify what you mean "it's in rigid body but it's not set"
my trigger has box collider but uiElement is not checked here's screen shot
or was it not the question?
show Player that walks in this trigger has
a Rigidbody/CharacterController & tag set as "Player"
I don't think so
I imagine something like this
- how do you know you're in the trigger at all ? you can't see the collider when testing
- are you moving the rigidbody with AddForce/Velocity in code ?
- is that box collider actually set to IsTrigger ?
Unfold the collider component and show what you have set for it
I walk inside the trigger in the scene
for the rigid body (character right?) it's from an asset i don't know how it moves
and yes it's set to is triiger
I juste changed the name of my character to Player and the text appears in the game test by unity but when I build it it doesnt show
what do you mean? the name should have no affect on this according to the code you wrote..
maybe I'm having a hell of a time wrapping my head around this.
Lets say I have 2 zones, a destroy zone and a level up zone. If the ball hits the destroy zone it destroys itself, if it hits the level up zone it's "XP" variable goes up by 1.
In this case, the ball would have the "dostuff" method, but thats only one method. How is it supposed to handle multiple possibilities outside of doing somthing like tagging the zones?
when i say to unity build and run it like that
whatever you did it was def not changing the name, maybe something else save and it started working again.. either that or youhave poorly anchored UI so you can't tell as well when it appears somewhere else..
no where in the code you sent there is anything about gameobject name checks
most likely, but i don't know anymore cause it works in unity but not when I say build and render
that could just be poorly anchored text getting out of screen in bigger resolution
why not center the text? just for testing because on the edge is difficult
or better yet make something really obvious happen for testing..
good news it shows when i go in the zone but it still dosn't change scene when i press "m"
No the DoStuff() would be in the zones, not the ball. That way the ball can have no logic on its own.
And you can create as many new zones as you like, as long as they inherit from the zone interface.
I think it would be bad practice to code each individual interaction inside the ball.
Maybe someone can chime in on this as well, I'm not too good of explaining this.
https://youtu.be/2LA3BLqOw9g?si=wL8F6K4U0acOqu1T Nice quick video on interfaces
Sign up for the Level 2 Game Dev Newsletter: http://eepurl.com/gGb8eP
In this video, you'll learn how to use interfaces in Unity3D and Game Development.
#Interfaces #Unity3D #GameDevelopment
The Interface is one of many programming concepts that can be utilized in both Unity3D and Game Development, in general. It's a powerful construct in obj...
okay the first part is solved. now instead of checking keys inside the TriggerStay loop, thats a physics loop, its difficult to catch a 1 frame event at exact time
You have to use update to capture inputs
so you either make a bool that you are insideTrigger with OnTriggerEnter/Exit then use that in update with keypress like if(insideTrigger && Input.GetKeyDown(KeyCode.M)
or
you can make a bool for KeyDownPressed, capture it in update then use it in the trigger.
sceneSwitchPressed = Input.GetKeyDown(KeyCode.M)
former is the cleaner option IMO
At 1:45 mark, this is the exact scenario of having all the different interactions on the ball script, it becomes spaghetti
so let's say I do
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MoveScene_OnKeyPress : MonoBehaviour
{
void Update() {"rest of code"}
}
read the message under that, should give you a bit more detail
I like the second one better
sure, it will work but probably wont be as good as option 1 tbh
but try it and see I guess
I will go to option 1 cause if you think it's better I will try it first
and if it work i will try option 2 later
yeah its pretty easy to do , basically same way you set bool for UI being activated / not but in a variable you can use in Update w keypress
just being pedantic, classes don't inherit interfaces they implement them
big difference in how inheritance work but its strength / benefit because of it
classes can't inherit multiple classes , but classes can implement multiple interfaces (their major strength)
Ye good point
I started coding in Python which actually support multiple inheritance, kind of cursed to think about when I've only used C# for the longest time now
Python is weird
I can't use it anymore lol, just too much weirdness
ok so I got this for now and unity tells me :
- it wants a ";" in the world "other" so it would look like the "o;ther"
- and I can't use "="
? sorry for your patience but could you still help me with it pls?
there are beginner c# courses pinned in this channel. you need to start with those.
what are you even writing..
i'm lost
yes you lack the basic c# probably something you want to be doing before anything
I think you gotta learn more C# syntax
Yeah but I need to present it to my boss on monday and I just started learning code
IDE not even configured but thats the last of your problems right now, you wrote some nonsense syntax lol
insideTrigger is a variable that doesnt currently exist... the IDE / compiler would tell you but your syntax is completely fucked..
oh
So yeah line 13 is nonsense, you're trying to assign the value true to a function, I don't even know what it's supposed to be doing
why did your boss assign a task you have no idea about ?
You use it like
private void OnTriggerEnter(Collider other)
{
//do stuff
}
it would be one thing if it was slightly wrong but this is like beyond that lol
Oh you have the other event functions set-up correctly 🤷
so basically I did a 3D modelling of a quarry and she was like hey it would be good if we could walk inside it and here I am
thats probably what they did, but now are in the classic "what did I get myself into, this is harder than I thought " when you have to meld different systems together
The fact that this code isn't underlined in red means your !ide isn't configured which would likely have told you this line makes no sense before you finished writing it
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Hello, i took a webGl build of my game, when i click on the game window in browser it highlights the game window, turns to blue, and disables controls. It goes back to normal when i double click. How can i fix this?
probably a better question for #🌐┃web
also would test different browser and see if its isolated issue
all webGL questions should be asked at #🌐┃web ?
tahts why I linked it
this felt to me like a code related issue but okay, thanks
if you think its somehow code related, you should probably show any relevant code
that's w
hat i did
No, i haven't wrote a code to create this issue but i meant the solution of issue could be the adding a right code. Like cursor focus options. Anyway, i'll try this on another browser first
Anyone.....please? 😕 Just need to be pointed in the right direction. lol.
So I'm working on this single player fps game and Im having a lot of issues making enemies for it, to start many enemies seem to not have a concept of front they just move around and shoot in whatever direction they want to , and that only happens when the enemy AI work , even with nav mesh and everything some enemies won't even move or detect the player, some won't even play the animations correctly
Now that I think about it I think i haven't made a enemy that works as intended , can anyone tell me how do get out of this hole ?
how to code
It looks like a bit complicated for a beginner problem, maybe ask in #archived-code-general ?
I'm actually making progress, just trying to figure out the maths to correct the second 'bar' (Right Side) at the moment (and then need to figure out why the texture isn't displaying red&white like it supposed to. lol.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Texture assigned in inspector via code.
It's not red and white because of the green color selected in the material... it's a multiplier, so red *green = black, white * green = green
I don't see width, height and equator in code and how are they set and whatnot... code otherwise seems fine 🤔
I'd probably just do it all in a shader, but hey
Ah okay, gotcha. Yeah that makes sense. not a big deal though really cause this isn't getting applied to anything, just doing that for testing to make sure I have my values correct. the right side 'bar' is beginning to annoy me. lol. And I need to do it in code to drive an asset based on values coming from an xml file.
Feels likq equator is not the correct value, but I don't know
oh, it's visible in the logs...
Yeah it is. textureheight/2
oh, stupid me...
of course that's wrong... it only works if the middle of your min-max is the middle of the side
This is an illustrated example of what I need to fix.
you need to check if it's between height - max and height - min
in the else if
what you made is "repeat after mid point", what you need is "reflect after mid point" if that makes sense
Yeah, it's the translating from 90-0-90 (top, middle, bottom) to 0-1024 (top - bottom) that's getting me. lol.
Yes, tile map collider. Also wdym make sure my physics shapes are right? I use click "used by composite" on the tile map collider. That's what I mean by using it, and those were the cons of using it, likewise if I just don't use it, I get the other cons
float Angle = Mathf.Atan2(look.y, look.x) * Mathf.Rad2Deg;
float fAngle = Mathf.Clamp(Angle, -30, 30);
transform.Rotate(0,0,fAngle);```
my value is not being clamped?
its currently at -84 as we speak
And what are you trying to do?
get the gameobject the script is attached to to face a transform (this transform being the player variable). If the player transform is more than 30 degrees away from the front of the gameobject, it will be considered out of sight and the gameobject will no longer rotate towards the player. This is a 2d game, and the code works perfectly except for the fact that fAngle seems to not be getting clamped at all.
transform.Rotate changes the rotation of the transform by the given amount, that is, for example similar as if you did current_rotation = current_rotation + your_angle
You're just clamping your_angle but the rotation still occurs, there is no code preventing that
If executed several more times it eventually face the player
Heya I was wondering if I could get some help, I'm trying to get something to spawn either on the left side or right side of the screen. The code seems to work when forced to pick a side by changing the range random can do to either 1 or 0 but when given the option it only picks left.
{
if (Input.GetKeyDown(KeyCode.J))
{
Instantiate(powerUpMGPrefab, RandomPowerUpSpawn(), powerUpMGPrefab.transform.rotation);
}
}
private Vector3 RandomPowerUpSpawn()
{
float limits = 4.24f;
int leftRight = Random.Range(0, 1);
if (leftRight == 0)
{
Vector3 spawnPos = new Vector3(-limits, 1, 1); //Spawn Left
return spawnPos;
}
else {
Vector3 spawnPos = new Vector3(limits, 1, 1); //Spawn Right
return spawnPos;
}
}```
Random.Range with integers is max exclusive. So Random.Range(0,1) can only roll 0
I'm unsure what max exclusive means, so would I have to do Random.Range(0,2) or just get rid of the 0 entirely?
Well from playing about rasing the number to 2 worked. Thank you for your help :)
when its max exclusive , you always want your wanted value max+1,
so yeah if you wanted range 0-2 you would put 0,3 and so on..this only for integer version
float version is max inclusive meaning the number you put doesn't need +1 cause its included in the range 0f,2f gives any decimal between0f-2f
Ah alright that makes sense, thank you so much for explaining it in detail :)
"Composite Operation"
also not a code question.
do newer versions not have the checkbox and it just becomes composite operation
yes it was changed in newer version
thx
!Learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Is there a way to pull all the api documentation for just the packages you have installed? usually when I am coding I have the documentation in a folder somewhere, and I just search within files the method I need info about and I can just get that info inside my IDE. heck sometimes I don't even have to click on anything
Anyone have a good way they get all the stuff in the same place to reference?
Hello dear Uniticians,
Im using the code below, to draw a ray to where the player is looking, and to move an empty object (that is marked by the sphrere), however even in play mode the ray and the empty object is somewhere in the very wrong place, where the player is clearly not looking. Thank you in advance for any help.
using UnityEngine;
[ExecuteAlways]
public class RaycastVisualizer : MonoBehaviour
{
public Camera playerCam;
public Transform marker;
void Update()
{
//nre check
if (!playerCam || !marker) return;
Ray ray = playerCam.ScreenPointToRay(new Vector3(0.5f, 0.5f));
if (Physics.Raycast(ray, out RaycastHit hit))
{
marker.position = hit.point;
}
}
void OnDrawGizmos()
{
//nre check
if (!playerCam) return;
Ray ray = playerCam.ScreenPointToRay(new Vector3(0.5f, 0.5f));
Gizmos.color = Color.red;
Gizmos.DrawRay(ray.origin, ray.direction * 100f);
}
}
have you tried doing Ray ray = new (playerCam.position, playerCam.forward); instead ?
That wouldve been too intelegent for me, ill try, thanks
might be the same thing but worth a shot, can you show gizmo for the camera transform in local pivot mode ?
Yep works, thanks!
can someone tell me why i get the error "The call is ambiguous between the following methods or properties" in visual studio on playerControls = new PlayerControls();, playerControls.Enable(); and playerControls.Disable();? heres the code: ```cs
public class playerController : MonoBehaviour
{
private PlayerControls playerControls;
[Header("Values")]
[SerializeField][Range(.01f, 10)] private float speed;
private void Awake()
{
playerControls = new PlayerControls();
}
private void OnEnable()
{
playerControls.Enable();
}
private void OnDisable()
{
playerControls.Disable();
}
private void Update()
{
Move();
}
}
ignore Move(); in Update i deleted it to shorten the code a bit
Is PlayerControlls also a mono behaviour by any chance?
yes its the generated c# class of my inputActions
Hey so take my word with a big big big grain of salt, but i think that your not supposed to use construct monobehaviours yourself
Better use gameObject.AddComponent or add it initially if u dont need it on awake and need it allways
it has always worked tho i used it almost since it came out
if it was generated class from input asset its not a MB
Shit, sorry, can you show the error exactly then (screenshot) as I didnt fully understand from your wording
wait i think ill try to regenerate the class as i now get errors in it too after opening
ah yes
good old unity bug
didnt know what happened but it worked after regenerating it
thanks for the help even tho it fixed itself haha
Np lol
Rat!
Hello! I need help figuring out a collision error with my player to the wall.
using UnityEngine;
public class playerMovement : MonoBehaviour
{
[SerializeField] Rigidbody2D rigidBody;
public float Playerspeed;
float moveSpeed;
float moveSpeed2;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
moveSpeed = Input.GetAxis("Horizontal") * Playerspeed;
moveSpeed2 = Input.GetAxis("Vertical") * Playerspeed;
transform.position += Vector3.right * moveSpeed * Time.deltaTime;
transform.position += Vector3.up * moveSpeed2 * Time.deltaTime;
}
}
all sorts of wrong here..
oh...
moving transform will teleport through walls , you need to use the rigidbody component methods
Rigidbody2D component you have to access the values with the . if you just started recently I would suggest you go through the unity !learn 👇 starters/junior courses they guide you through learning rigidbody movement and more.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ok, so theoretically, it would be something like "RigidBody2D.movePosition" right?
it has that but thats for kinematics. its usually https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html
or https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Rigidbody2D-linearVelocity.html
ok thanks!
In my game, waves of enemies can spawn. There can be different enemy types within each wave.
If I wanted control over spawn patterns (for instance, one large enemy in the middle with 3 small enemies in front), how do folks go about modeling this? I could quite literally have several code files that denote enemy type and location to spawn them in, but I'm wondering if there's a prettier way
It almost feels like I could be doing a prefab and building this in the editor drag/drop
would create some sort of data structure that defines that
store it in scriptable objects or something like json that your system ingests
Could use some help here
using UnityEngine;
public class TileScript : MonoBehaviour
{
TileController tileController;
// Start is called once before the first execution of Update after the MonoBehaviour is created
private void Start()
{
tileController = GameObject.FindFirstObjectByType<TileController>();
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
print("it works!");
tileController.SpawnTile();
}
}
}
trying to spawn a tile when the player leaves a box collider trigger area. neither printing nor spawning occurs. i have a feeling i just didnt implement my trigger correctly but im not sure. player has player tag and has a rigidbody, the collider in the tile is marked as a trigger, so idk
The SpawnTile function is a public function in the tilecontroller if you need to see that as well.
that embed didnt work at all lmao
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
` not ' 
put the logs outside the TagCheck
fixed. i had a box collider attached to a cube as a child of the tile, rather than the collider being a component of the tile itself. worlds biggest idiot award goes to me 🤡 thank you for your help tho i appreciate u
where should i get started in learning c#, there are alot of videos and idk what one would be the best to get started with (i do have prior knowledge in code, so i know the basic functions, loops, variables and all that)
any idea why my game view is just all blue? please tell me if you need more information
i literally just started but i feel like its the skybox
Show us the components on that sprite you have
Skybox
the black and red thing right?
Change the color of ur skybox if u dont like the blue color
The sprite isn't appearing in game
Hmm what's the position of the camera then?
Is the sprite supposed to be a ui thing or a world thing
i have it set to go towards the player
The camera needs to be "behind" the sprite(z position is -10) in order for the camera to see the sprite
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Run the game and help me check the position of the camera
ty
@wise cairn
ok thanks
its the player
In that case use cinemachine and have it follow the player
what is that
yeah thats what i was doing
HI
how to declare array of arrays in correct way?
i tried Vector3[][] myArrays={new Vecto3[],new Vector3}
but it didn't work
Vector3[][] a = new Vector3[][size];
//Then init each sub array separately(for example in a loop)
a[0] = new Vector3[subSize];
I've got this script for managing stats on my characters but I can't get the _basevalue and _modifiedvalue to show in the inspector, any idea's why not?
The BaseValue and ModifiedValue show up but if I set the BaseValue in the inspector the game just ignores it and when I try to fetch the data it resets to 0
do u declare an instance of this class anywhere? this is just the class
This is where I create the attributes
[System.Serializable] public class Attribute { [System.NonSerialized] public RemnantEquipmentAndStats parent; public RemnantStats statType; public ModifierInterface modifierValue; public void SetParent(RemnantEquipmentAndStats parent) { this.parent = parent; modifierValue = new ModifierInterface(AttributeModified); } public void AttributeModified() { parent.AttributeModified(this); } }
this is still just a class. you need to declare this on some unityobject for it to show up anywhere
The attributes are in an array in a data class for a list of characters kept in a Scriptable object
it shows up like this
I have a list of modifiers for adding modifieres to the stats non destructively, but I've been getting a null error for this list, could that be the issue?
public List<IModifier> modifiers = new List<IModifier>();
this is where it returns null
public void UpdateModifiedValue() { var valueToAdd = 0; if (modifiers == null) { Debug.LogError("Attempted to update null modifier"); return; } if (modifiers.Count > 0) { for (int i = 0; i < modifiers.Count; i++) { modifiers[i].AddValue(ref valueToAdd); } } _modifiedValue = _baseValue + valueToAdd; ValueModified?.Invoke(); }
Okay, very confused. Not a coding question but tbh, I can't really see anywhere to post.
But, CharacterController step offset is weird and I really don't get it.
Calculator result is Height + Radius * 2 of the Character Controller height & radius, as the error says. But i'm still getting the error.
It's truly baffling how this works tbh. The errors only disappear when I put the step height to around 0.2 😕
Attack 2 is not working after Que attack, what is the cause
public void OnAttackAnimationEnd()
{
Debug.Log ("OnAttackAnimationEnd called");
if (queuedNextAttack)
{
queuedNextAttack = false;
comboStep++;
StartAttack();
}
else
{
isAttacking = false;
comboStep = 0;
animator.Play("xVelocity.Idle", 0); // Optional: return to idle state
Debug.Log("Combo Ended");
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
#💻┃unity-talk but PEMDAS rules apply. 0.19 + (0.02 * 2) = 0.23
Ah dammit. Yeah, the error isn't overly clear on that point. lol. Thank you.
LMAO. Even doing that, calculator result = 0.23998908
enter 0.23, still get the error.
Anything above 0.2 I get the error. (even 0.201), sod it, 0.2 will do for now.
wtf? Now it's changed its mind and anything above 0.195 throws the error.
Is there any scaling going on?
Okay, this is massively weird.
Because the 'working' step offset value was so close to the 'height' I tried this.
and yeah, weird but if the step offset is higher than the height, it throws the error. lol.
Okay, I'll go sit in the corner. my main root object isn't scaled, but the actual character model is, so I'm guessing the value of 0.23 should actually be 0.023
I forgot I'd done that. lol.
это ты чо такое наделал то?
Anyone needs help? :p so many unanswered questions above
Those seem to be the correct fields showing up. Your property BaseValue isnt what youre seeing here because properties arent serialized. Same with modified value.
I dont really know what your IModifier is because you never showed it or a class that inherits it. I assume a unity object is inheriting it (like a monobehaviour). In that case, your null check isnt using unitys null check and you'd need to cast it to a unity object
how do i subscribe a function to an event?
assuming you mean on a button, myButton.onClick.AddListener(() => MyFunction(parameters));
or if it's a standard C# event, myEvent += () => MyFunction(parameters), or even just myEvent += MyFunction if the event parameters match the function's
I sometimes come here when I'm bored too 😅 (bored = procrastinate-y)
ah i see, thank you 
Hi, I have this struct in Unity:
https://hastebin.com/share/gozotevuvu.csharp
I have to have the constructor with all the optional parameters but would also like to have default serialized values in the inspector.
Is that possible?
Thanks in advance and please @ me.
same, gives me a good excuse to not work while simultaneously learning something new. or atleast feel like im doing something productive lol
Was there some AI shenanigans when making this code?
This isnt a struct and there's pretty weird logic in that. Like why are all those vectors nullable if youre just going to assign it a specific value if null. Just skip the nullable and assign the default value in the parameters
If you want it to have specific values in inspector too by default, you do the same thing you would do in component. Assign the value on the same line where you declare the variable
It's more like "you don't have to pass them", no? You can't have a default for a struct. 🤔
Nope, written it myself.
Not a struct?
As for vectors being nullable, I have a simple explanation.
I want to allow users to still input Vector2.zero(aka default) while making sure that if not assigned by the user(null), I assign the default value.
And lastly, why don't I just assign a value in params? Take a look at the picture below.
ah, my bad, I said struct instead of class, p fried atm
where does this "serialized bla bla ignored during serialization" come from? normally doing public Vector2 VolumeRange = Vector2.one; works fine
do you have a list of those classes by any chance?
nope, let me just define it as a field in a class
[SerializeField] private AudioItemSettings set;
You dont need the nullable at all here
sure, I am open to suggestions
This is what I get without the attributes, so I blame them 🤷♂️
odd, let me try it on my end rq
#💻┃code-beginner message
The suggestion was what Pulni was also writing. My mistake on the parameter part
That sadly didn't work.
I removed literally every single attribute in that script, readded the script and still the same :/
and also, wdym by works for new instances?
rip
automod doesn't like single word messages. i think it would've worked if you said "unity 6"
or just extended the message some other way
ye, anyways, if you got ideas as to why I can't have default values on these fields just @ me
it's 99% not the attribtues as I removed them, and rider also suggests that there's a deeper issue
I see, how come it worked for Pulni?
Is it a Unity 6 bug or sm?
definitely a weird bug though. (assuming the thread is correct and i didn't misunderstand anything)
i might need to mess around with this myself and see if i can find anything
according to the thread, it's been an issue with unity for a while, they just never got around to fixing it.
although, let me try it on my end real quick. i'll see if i can come up with anything new
This seems like a major issue, odd that it hasn't been taken a look at for so long.
That's why I asked if it's in a List. They tend to not work in lists. I tried to do a workaround before, buut I think it was getting way too hacky or something and I noped out.
nope, not a list, it's always a field, or a field of a field
If you have a serialized object and you add an initializer value, the objects that are already serialized won't get the new value. Won't even work if you add a new field that's initialized.
Or at least I think it might be the case. I can test it later.
My point was to do it without the attributes and make a new instance of the thing that contains the field or at least reset it. See if that makes it work.
I'm moving items from inventory to chest...
When I have a stack of existing items to fill, this means changing the amount number in chest and deleting the item from inventory.
Items are just game objects with a script and child object that has canvas renderer + image (which has child for amount text).
In method for filling partial item stacks, I do "Destroy(sourceItemUI.gameObject);", but nothing happens. The game object is not being deleted ever.
If I do DestroyImmediate, it will get removed as expected.
What is happening here? As I understand, DestroyImmediate should not be used if possible due to potential unexpected issues (that I didn't investigate too closely atm)
Just tried adding the component to a completely new object, if that's what you were saying, still the same sadly.
Ok wait, this might've just answered my question...
https://discussions.unity.com/t/unity-ignoring-class-member-initialization-value/893010/5
I need a parameterless ctor 🤦♂️
yeah that was it, excellet :/
got there in the end
Oh wow 😄
im only on understanding methods of the book at the moment. I must say it is quite hard to not worry if i am wasting my time trying to learn it. I am worried im not smart enough for later in the book 😅 I struggle with a learning disability but I am so determined to acquire this skill. Sorry I know it is not a coding question I just thought I may feel better after talking with people who are good at this hahaha.
keep it up, we all started small
that is true, thank you I appreciate that. Hope your projects are going well
guys i wanna add in day versions and night versions the day scripts (for example day1 script for the first day) and i will have like 50 days but the problem is that i cant put the scripts inside of these can someone help me?
are the scripts attached to a GameObject?
no i dont wanna attach the scripts to a gameobject because like i said there will be 50 days and i will have to create 50 Gameobjects
and if i attach the scripts to the gameobjects it will be soo massy
i dont want that
Wait what ? Why do you need 50 scripts for 50 days ? 🤔 It should be only 1 script for all the days 🤔
i will make texts for each one
what texts ?
in this box will be wrote the texts of the each day like in day 1 there will be text options for day2 script the options will be different
Ok then you're approaching the problem the wrong way, the script that handles your day should only be 1 not 50. In that script you can add either an array of strings where you put your text, or if it's more complicated than that use Scriptable Objects, and each day you switch to the right one
your script expect the script "Day Script" not day1 script, correct me if im wrong
yes but all scripts inherits from Day Script
hm makes sense but
how can i make options like for each options
in order to assign a reference to a script in the inspector, it has to be attached to a GameObject
What do you mean by that ?
like i wanna code these SOs like if this gameobject got selected then this happens specific
Could you explain what kind of text are we talking about ? Is it just "Day 1", "Day 2" written on your HUD screen ? or some dialogue (with or without answers for the player to click) or quests ?
dialogue
there will be a lot of text in each day
Follow this : https://youtu.be/hG6EMeArp04
Get it here: https://assetstore.unity.com/packages/tools/behavior-ai/dialogue-system-for-2d-3d-games-311097
Games in video
https://www.kickstarter.com/projects/petermilko/the-last-phoenix
https://www.kickstarter.com/projects/alienpuppygames/meet-again-heartwell-otome-game
#unity #gamedev #dialoguesystem
On Day1 there it will be like
string[] dialogue;
dialogue[0] = {
text = "hello world";
type = Types.NotQuestion
};
ok lemme watch
Yeah don't do that, it will be painful for you to do and to maintain
how should i do that then
like the video?
Watch the video
yes
that's kind of similar to how i manage my dialogue in one of my projects. i have a dialogue class which i serialize in the inspector and then send over to a UI manager when it's triggered.
it must have been painful, isn't it 👀 ?
at first it was, that was mostly just writing the script though. only problems i have with it now is that i forgot to add comments lol
the video u sent me dude uses a package and its very very complicated
and i wanna make my own dialogu system which is not messy and not hard to make
it takes a bit of time to get used to it and learn it but once you do you will understand why it's better to go that route than doing yours the way you wanted to do it 🙂
the way i wanna do it is bas i got it. Ima try to look up it on youtube. Because the thing that i wanna make is like dialogue system. If i still cant, ima write here and try to make another way
Pulni, I was SO bored that I just opened this server for literally 1 minute 🤣
It's fun when it's busy and there are questions to be answered, but yeah at "I'm bored" times every server just seems to be empty 😛
It's the worst! AI is stealing our fun, our opportunity to escape from boredom! 😂
Can anyone tell me why I can't see my hands but I can see my weapon?
camera near clipping.
also not a code question
Does anyone have any useful tips on how to deal with enemy cluttering? To give more context the tracking script is fairly simple:
private void MoveTowardsPlayer()
{
transform.position = Vector2.MoveTowards(transform.position, player.transform.position, speed * Time.deltaTime);
animator.SetBool("isAttacking", false);
}```
depends what your goal is but simplest would be to have a variety of enemies in the encounter so that you don't have to deal with it 😉
I'm in the process of building out the core gameplay aspect of my project rn. eventually i'm going to add new enemies with different behaviors but if i spawn 2 of the same enemies within the level i don't want them to clutter up
if you look at games like doom, the generic melee enemies are really slow so that they mostly don't end up clumping before they die
well now I don't know what you mean
2 enemies in the same level shouldn't clutter up? what does that mean?
oh you're just moving their posisions so they are literally inside each other
yes
you could probably toss colliders on them
otherwise yeah, roll your own spacing system, but it depends on the kind of game whether that makes much sense
they do have colliders
you need it for an RTS but in an FPS you are probably better off designing enemies that don't swarm the player so effectively
hmm well my recollection is that that should work but you might need to move them via their rigidbody instead
Hey im new to unity, anybody knows how to make a simple 3d Map?
im trying to make a simple game similar to schedule 1 but with completely different mechanics
This isn't a coding question. !collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
how is this not a coding question
💔
coding and mapping are 2 separate components when it comes to game building. I recommend finding a great beginner tutorial on youtube!
Not realistic. Set yourself on a smaller / simpler goal to achieve
is there a way to make a UI Toggle button show 2 different icons on click? I want to have a thumbs up for on and a thumbs down for off
i mean now I only want to create a simple map
Okay well you asked in the wrong channel.. this is a code chqnnel... if you want to learn go to the unity learn website !learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Okay, then show your script
If it's a coding question, post !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hi nav just wanted to tell you I was able to finally do what I was looking for yesterday with this code bellow, and thanks a lot for your time it really helped me a lot just a quick thing about the key down, when I said press "M" it would'nt do anything and when I said "A" it only worked when I pressed the "Q" key is it because I'm on AZERTY or is it something else, cause I then put it on "P" since it's the same position in AZERTY and QWERTY.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ForMainMenu : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.P))
{
SceneManager.LoadScene("MainMenu");
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
}
and also thanks for all the other that also helped me and pointed other things
is there a way to change a toggle button so the checkmark doesnt disappear when you click it?
Probaby , but if you need to have custom behavior or images why not just build your own system with iPointer interface
Hey I'm trying to use the 2d multiplayer prefab but I cant figure out how to edit the scenes/make new ones, can someone help me?
if you can't modify prefabs should you be doing anything multiplayer related 
Could anyone recommend a video or article explaining the weighted list class? (the simpler the better)
is this in a build?
what weighted list class
class WeightedList<T>
I don't think that's a class provided by unity or c# by default
oh is it not?
In general: if I first launch the game,
it is not, no
ouch, that was a perfect solution
you could make it yourself
but it doesn't really sound like it needs to be its own class
ah wait i misunderstood the "weights" aspect, i was thinking of priority
I copied this off of google ai summary so i cant really tell where i got it from
and now i cant find anything on it
lol lesson learned real quick, eh
googling "weightedlist unity" gave me plenty of results though
does anybody understand why this collision isn't working?
private void OnCollisionEnter2D(Collision2D collision)
{
Destroy(gameObject);
}
thank you
Hello! I have a few questions regarding setting up Unity for coding.
I am using the version 6.1 right now.
- How do I set it up for Visual Studio Code as I don't see the package in Package Manager.
- Everytime I try to work with
Input.GetAxis("Horizontal");it gives me an error that, that way of doing things is old.
!IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
as for the error you are getting, it isn't saying that is old. it is saying that your project is currently set up to use the input system in the active input handling settings. it even tells you that setting is in the Player settings so you can go and change it if you intend to use the input manager
I'm at my wits end with UI stuff. I have a game object with a box collider and several children. I have a script that has both OnMouseEnter and OnMouseDown but neither of them are activating
Would you suggest 6.0 or 6.1?
I could be wrong but I think those only run for the collider attached to the same gameobject. That’s at least how OnTriggerEnter, etc. work.
use whichever version the course you are learning from uses
In other words those event functions will not run as a result of the mouse entering colliders in child gameobjects
I have the Box Collider 2D and my script on the same game object
if you're using the Input System rather than the old input manager you'll need to switch to using the event system interfaces like IPointerEnterHandler because OnMouseXXX does not work with the input system
Which course would you recommend?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
How about layers? And is there anything that could be blocking the detection? Like a canvas that’s blocking your collider?
Wait really? I didn’t know this
Using the IPointer interfaces are better in most ways anyway. Just not automatic so it requires more setup
everything here except camera and eventsystem is on the UI layer
Per what Boxfriend shared, these functions apparently won’t work if you’re using the Input System rather than the legacy input manager. Are you using Input System?
I dont know what Input System vs input manager means
Hello, i'm using OnMouseEnter() to debug why onmousedown has issue. And as you can see the enemy is causing the OnMouseEnter keeps incresing and is incresing even more rapidly with the speed of the enemy ( there is no issue when the speed is 0 ) Do you know why ?
I know that some fix is to use raycast or idk but i rly want to udnerstand wtf is happing here
thx !
Id replace this and use Pointer events with an event system instead
Requires an event system to be in the scene AND the corresponding physics raycaster component too:
https://docs.unity3d.com/Packages/com.unity.ugui@2.0/api/UnityEngine.EventSystems.Physics2DRaycaster.html
This will then work using 2d colliders for example.
I use this a lot and im happy with how it works in 3d and 2d
a channel in the server?
there are 2 channels with "ui" in the name
nono i am asking because rob mentioned IPointerEnterHandler
that can be used for world space objects
then this is new to me
did you not think it was odd that rob said they needed a physics raycaster component? that is obviously unrelated to UI, it's what makes it work for detecting colliders in the world
fair enough, did not see that part
Yea its used with ugui but also works with 2d and 3d physics
ugui elements DO block the raycasts too which is usually a good thing too
as its all the same system, meaning no dumb work arounds checking "is cursor over ui element"
What's the general vibe for those who want to use SOAP to reduce the dependencies of GameObjects to each other?
Using events or interfaces or sub classes should solve this
I'm struggling to do something like... I have a ProjectileController with a ProjectileHItboxBehavior on it, and an EnemyController with an EnemyMovementBehavior on it. Behaviors are children, controllers are the "root".
When a projectile collides with an enemy, it should raise an event that a collision occurred. Right now, this event exists on the EnemyController, so I have to have a behavior reference another controller, to invoke the event.
When the event is invoked on the EnemyController, and can then inform its behaviors (e.g. MovementBehavior, VisualBehavior, AudioBehavior) about the collision
This feels like a lot of knowledge sharing and boilerplate and I don't quite know a better way. It seems like it could "all be solved" if every involved party (ProjectileHitboxBehavior, EnemyMovementBehavior, EnemyVisualBehavior, etc..) could just reference the same event scriptable object.
if you split things up too much you may be inventing the problem
You think what I'm doing is somewhat overkill?
maybe, if its not helping or providing benefit having things be separated soo much, why do it?
I know it will
A projectile probably will deal with collision so why does it need a seperate component to handle collision?
The movement/physics in my game alone is quite a lot of code, I don't want to mix in audio, sprites, particles, etc..
Essentially what I'm trying to do is have a system of parent/children, where the parents orchestrate and the children get fed data
Then its either manually made events, some event bus or explicit dependencies passed around
That's why I think SOAP aligns with how I think
I can define an event as a first-class asset in my prefab to be invoked by others
You can use public Action MyEvent; as field in any class and then asing it from any place
at first i was thinking you were talking about SOAP like the message protocol.
ive never seen a proper use for scriptable objects as events. it really doesnt provide you anything here other than just moving where the event happens from. You aren't reducing the dependencies, you're just hiding them
Hah, no, I deal with wcf and SOAP enough at my job I have no intention of willingly touching it
Ultimately I just want to see if I can reduce my boilerplate and the fact that references to my root controllers need to be shared to trigger events
are your "controllers" the scriptable objects here? its really hard to follow logic or what is really the struggle here when we dont exactly see what the system is. If you want to separate things to this degree, yet have everything go through 1 controller, everything has to reference this controller or each other either way.
And my children subscribe to the toot controller’s events
I’m not using scriptable objects yet, everything is a mono behavior
So I guess - assume for simplicity's sake that every gameobject look ssomething like -
FooController
FooAudioBehavior
FooVisualBehavior
FooCollisionBehavior
FooMovementBehavior
Everything here is a MB
then tbh i dont see what the problem is or how "it could all be solved if every involved party ... could just reference the same event scriptable object". Every object here can also just reference the FooController
So if I want something like the ProjectileCollisionBehavior to be able to notify the EnemyController that it just hit, to say "hey mate you just got bumped, here's how hard"
e.g.
public void OnCollide(ProjectileController projectile, GameObject target, Vector2 relativeVelocity)
{
if (target.TryGetComponent<EnemyController>(out var enemyController))
{
var direction = (projectile.transform.position - enemyController.transform.position).normalized;
var velocity = relativeVelocity.magnitude;
var pushForce = Mathf.Min(velocity * ForceMultiplier, MaxPushForce);
enemyController.OnCollide.Invoke(direction * velocity * pushForce);
}
}
Now all of my behaviors in the EnemyController like audio, visual, movement, need to subscribe to the OnCollide event
The way I see it, it makes my behaviors dependent on their parent Controller, and it requires other components to resolve a reference to the Controller they want to notify
Maybe I'm overthinking it and that's just "okay"
Maybe I could define the OnCollide event at the root level of my Enemy prefab, and instead of resolving the controller, I can try to resolve ICollidable on the target of my collision
And then my enemy behaviors could subscribe to that, instead of it being on the controller.
they are dependent because they depend on it existing. Think about it like this, would EnemyVisualBehavior or EnemyMovementBehavior ever exist without a EnemyController? your game probably would feel wrong if an enemy made no noise, so to some degree you also rely on every character having some kind of AudioBehaviour.
for that method above, idk where you would really be putting this. It doesnt make sense that a projectile would be hitting a target and then have to call that method above. The projectile should know its direction already and should try getting the enemy controller from the beginning to notify it was hit through calling a method. You ideally wouldnt be invoking a characters OnCollide method yourself, the character should do this by themselves
the only other concern id have would be that you have a projectile specifically trying to target an EnemyController rather than some base Character which can apply to your player as well. Right now you would need separate code for the same projectile to hit a player
Hey! Genuine question: Do ya'll write most of your code without tutorials? It's been so tough writing code on my own even when it came to writing a CharacterController movement script...
I've been struggling lol
I might be in "Tutorial Hell" but I've tried creating the simplest games on my own and just couldn't
hello following this issue i found that i can do a raycast of lenght 0 :
RaycastHit2D hit = Physics2D.Raycast(worldPos, Vector2.zero, Mathf.Infinity, tileLayer);
is it inconvenient in some cases ? it feels like a hack and i still don't know why i had my issue earlier
I write my code with tutorials named "documentation" and "research".
The best way to tackle a problem is to break it down into separate steps and solve one at a time. If you're stuck on a single step instead of a whole complex problem then it's easier to search for a solution.
But of course, start with !learn if you haven't done so already
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
personnaly i advise to stop looking at youtube for a bit and only google / chat gpt ( try not too mych gpt too ) so you'll focus more in understanding than copy pasting
Just start being okay with being wrong. Come up with an idea and attempt it. It probably won't work. Then start trying to figure out how to make it work which will be easier because you have it at least somewhat formed. Repeat until the "won't work" step starts becoming rarer and rarer
Do you guys recommend any unity c# book
@formal tide I would recommend you this videos https://www.kodeco.com/3247-beginning-c instead a books
Learn the basics of C# in the context of Unity in this FREE comprehensive screencast series.
and for Unity there is a lot learning material on Unity3d site and Documentation
Thanks
Is this free. I guess i need to create account
it was free
Can i find every method in there
Every method that exists in unity
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
U can find every think you need there https://docs.unity3d.com/Manual/scripting-get-started.html
I doubt that
Well i guess i need to do examples because i wanted to do my own code and i couldnt
I wanna make my camera follow my ingame character(cube)
I couldnt do it
Just google there lot of such examples or use ChatGPT it can give you examples too
Do u guys have any recommendation how can i writr my own code and learn it rather than followin tutorials and copyng pasting
dont use chatgpt, it's shit
chatGPT give simple code but for something complex it is shit
!learn is the easiest way
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
its shit for simple stuff
Yeah im using deepseek on the side
Alright i will watch this again
Im learning so slowly
What do you mean watch it again theres over 750 hours of content
check this https://docs.unity3d.com/Manual/working-with-gameobjects.html if you need to work with gameObjects if you read step by step you will have all info you need
Uhh i watched just one tutorial. He was making a game
First one
Rolling a ball isnt the only thing there is
Yea i have this link on the side as well
The thing is im learning veery slow. Everyone said i can learn basics in 2 weeks. I spent 2 months for basics and not fimishrd
Finished
Is this normal
You can spend years to start writing good code
Yea
and you can create somthing by following the tutorial and modify it in a months
Thanks
And also stop using ai for this
Alright
When I started I watched only video tutorials I was able to create feachures I need for my games by just googling and add feature by feature to my game. If you start developing you should also google Scriptable Objects it is not oblivious Unity3d feature but useful
I tried to write wasd controls and space for jump code. It works but i guess i wrote it too long
Is this good code or too long
if it works, dont fix it 
-# (until it becomes a massive issue later)
Multiply by time.deltafixedtime and put the entiew thing in fixedupdate
Do u recommend i should just start develope my own small game and learn on the road. I do small prototypes right now some mechanics and try to learn likr that
Yes you should start your own game and finish the prototype
Hmm alright
I usually use if (Input.GetKeyDown(KeyCode.A)) { } your mthod I see first time
I should check what all that means
You can also read the Unity3d tutorials there lot of things you can learn
This is the old input system i believe. Mine is new input system. 🙂 i dont know the difference tho. I did urs first and it worked fine then i tried new input system
honestly for me the old looks better 🙂 because u have class with all KeyCode, but it is okay to use any that works
yeah the old input system is probably better for beginners. the new input just makes things like adding controller support easier (afaik atleast)
Can someone help me i watch one video and i wrote the code for moving left and right but my player does not move but does not show me any kind of error
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
is the script attached to an object?
Yes
@manic blade You need to do Input.GetAxis("Horizontal") * Speed and check the Speed value that will move fine for you
I do not remember try 10f if to slow try 1000f
I did that i put 100 still didn't move
should still work even without multiplying by speed. if they were just using AddForce then that could be the issue but they're directly setting the velocity
the script looks fine to me. the only issue i can think of is that it just isn't attached
I can send you an picture it is attached
-# sidenote: use screenshots instead of another device. makes the image more clear
I was trying to fix it didn't work before i added the speed
everything looks correct. you definitely entered playmode and then pressed A,D or the two arrow inputs
yes
in the screenshot the class is named playermovement
but this is another script called palyermovement
if it's not that, im officially out of ideas 
In unity project settings from top left then player settings find activated input settings or whatever that called. I changed that to"both" And it worked. I had the same issue but idk if its same issue for u. Maybe u can try
that was an old screenshot i fixed that
Alright
I recreated the logic it is working fine
could be this. i've mainly used the new input system ever since swapping to unity 6 so i cant really confirm or deny that.
here i changed this to both now both input system works
i did that i tried everything that why i came here
Did u try using Debug.Log so u can see the error
no
I would try that to see what is the issue
ok so i'm making a 2d side scrolling game and just working on basic movement, how should i move the player? i already have all my code calculating how much to move and rb.position += movement * Time.fixedDeltaTime was working, but apparently i shouldn't do that because it ignores physics? what do i do instead?
why does the collider have a scale of 5.12? assuming that's the default square sprite, a scale of 1 on the collider should just automatically scale correctly with the object
take a look at this video
DeltaTime. This video is all about that mysterious variable that oh so many game developers seem to struggle with. How to use DeltaTime correclty? I got the answers and hope this video will help to deepen your understanding about how to make frame rate independent video games.
0:00 - Intro
0:34 - Creating The Illusion of Motion
1:11 - Simple Li...
ok thanks
Also did u see that Awake() method? Can u change that to Start() Im beginner but i guess that method is not neccedary there
Did you press the Play button to enter play mode before move object xD?
right yeah use rb.linearVelocity (or if you're using an older version, rb.velocity) instead
yes
i will try
if you directly change the position of the object i believe it'll cause clipping
for my it didnt change
awake just runs before start. i dont think it'll cause any issues in this scenario
(the unity docs has a useful graph explaining it)
Hmm i never saw it thank u
i can send an video because i don't know what to do
delete the player create new one add The Sprite the Rigidbody2D then add the Playermovement hit play and try agian:)
i will try if it dont work im gonna start some other way
its actually better to have the graphics as a child gameobject
@manic blade Rename script form playermovement to Playermovement
- Player - rigidbody, collider
- graphics - sprite
but ya.. something like that
Your script playermovement.cs it should have same name as inside script
lol.. it angers me that my classes and scripts no longer have to match
try to rename this one maybe will work in older unity it should match
they are using Unity6 , that doesn't matter rn
what they should do though is not have the Console tab/window hidden
sum like this
i have uniy 6 and rename it still does not work
where did you put playermovement component at ?
put logs inside the script and see if thats running at all
you put logs inside update ? check the console after doing so, press some keys etc.
how do i do that
Debug.Log
should've been the first piece of code you should've learned
Debut.Log(Input.GetAxis("Horizontal"));
better yet store it inside a variable
float horizontalMove = Input.GetAxis("Horizontal");
Debug.Log($"input value {horizontalMove}");
when you press <- -> or A D it should log 1 or -1 if it log 0 mean input does not working
its an dumb question but where should i put it i was only following an video
inside Update
like I said, in Update
@manic blade did you follow this Edit->ProjectSettings #💻┃code-beginner message ?
like diss
jesus..
even the editor is yelling at you , you forgot to put;
that tells the computer , this is the end of a line of code
i forgot
Consider doing the intro to C# course in the pins
If you won't even understand how to implement any advice you get here it's going to be hard to get any advice here
i am going to but when I was looking for a solution i joined here
until the next problem
Learning the bare minimum basics of writing code will let you actually use any answers you get here
thanks for trying to help i am going to learn more than try to make an game
How do you detect when a button is released with the input system?
Canceled event
there is also WasReleasedThisFrame if you don't use events
@tulip relic In old Input.GetKeyUp
What are you talking about?
Also, my PlayerInput is created at runtime without a prefab, so I'm not sure how to assign UnityEvents to it
wdym "PlayerInput is created at runtime without a prefab"
The component is added to the player GameObject from a SpawnManager at runtime
if you're using the PlayerInput are you using SendMessages mode?
I believe so
I usually use events, you can probably just check
inputValue.isPressed is false in the method for the action
What event is called when the button is released though
for events its .canceled
What method name
What is the name of the function
thats not events then.. in SendMessages mode, the method name is always the name of the action prefixed with On
In SendMessages mode, OnAttack is only called when the attack button is PRESSED, not released
eg cs OnAttack(InputValue value){ if(value.isPressed) //stuff else //was released
The //was released will never execute because OnAttack(InputValue value) is only called when the attack button is pressed
pretty sure it gets called on both
whenever I used it, it always called the method twice, once on pressed/held and once more released
I used
public void OnAttack(InputValue inputValue)
{
print(inputValue.isPressed);
}
and it only prints True
you might have to switch the action mode then
Where and to what
whats it currently set to ?
Are you talking about where it's set to "Button"?
in the actionmap, is it set to button?
In the Input Actions Editor, it's set to "Button"
isnt it action.started += context => Debug.Log($"{context.action} started"); action.performed += context => Debug.Log($"{context.action} performed"); action.canceled += context => Debug.Log($"{context.action} canceled");
What's action and where does that code go
InputAction class
like this var action = InputSystem.actions.FindAction("Move"); as I understand and action.canceled //triger when button Up
try setting it as Control ValueType - Any
if they were using events, this is event based as mentioned earlier you would use canceled
I'm not sure what this means
instead of Button, set it to ValueType
it should give you the secondary event of released
It does, thanks
actually for button iirc you can also add the Interactions for release
you can also set up Interactions per action
💪 i just happen to have it open..
still dippin my toe in.. but darn is this thing universal af
so many options 😵💫
i know.. its quite overwhelming if im being honest
been practicing with just a couple of buttons only
The new input system looks so heavy, not sure it is worth to use it.
clear it out and start fresh.. and its not soo bad anymore
I would not use anything else. old Input class is garbage in comparison
technically new input can be just as straight forward if using traditional polling
after a bit of fiddling i got a decent little system set up ^
and if u want.. u can still poll for inputs with it..
Update(){
if(Keyboard.current.spaceKey.wasPressedThisFrame)
{
// input.getKeyDown
}```
ezpz 🍋 squeezie
im still a bit intimidated by the axis' inputs but it'll be fine
"composites" rather
Okay maybe worth for action pc games. And not worth for mobile games (custom control usually).
totally false. this is actually especially good for mobile especially with all the custom Tap and other Interaction modes
you would need to code those manually with the old input
slowtap, multi-tap etc.
it also supports a variety of controllers and input devices
Yes, I used to setup mobile input manually and it wasn't hard? So new input is easier to do such operations?
In my opinion yes, and I used old input for years before taking the plunge and never looking back
it can be overwhelming because so many ways to do something in it
once you wrap your head around all the features you will pretty much love it
For example won't u need to use native mobile control if you develop swipe combat system I think it won't be available for default in new input
swipe is done the same way you do it with the old input system, track the magnitude between 1 point to another
many ways to get events such as TouchStart etc.
So this is point I do not need any additional knowledges to create any mobile control I need, but I will need to study a lot to implement new input for mobile game, and I will need to know how to use native mobile input even if I use new input.
is there a way to negate the destruction of an object in OnDestroy() (or in a different built-in method)?
i ask this under the assumption that OnDestroy() triggers before the object is actually destroyed
you could store an instance of an object and then instantiate that instance when it get's destroyed
i think i remember something about this causing issues though. so i'd avoid doing that if you can.
ah that's a neat idea, but then any references to it would become and stay broken
oh good point, that would work with prefabs but not individual instances.
i think so atleast, might have to test that myself
if you dont mind me asking, why are you trying to do this anyway?
it was just a random thought that intrigued me. i dont really need this for anything
when i use that for some reason the built in gravity breaks
you might be setting the velocity instead of adding to it. you can also just do like = new Vector2(movement, rb.linearVelocity.y)
create your own method, then this method can add logic basically choosing if it should call Destroy or not
is linearVelocity not conserved? does it only last for one frame?
yeah im sure i can go for that approach, but i was wondering if there was anything easier by using built-in methods
assuming you have some kind of drag, the velocity would slowly decrease.
what does drag mean? sorry if it's obvious, i have an idea but i'm just making sure
setting linear velocity overrides all that
yeah but the whole thing they were saying is to not set it
basically, anything that naturally slows the object down. usually it's linear damping although it could also be friction
oh true, i completely forgot about that
ok so still how should i move the object? adding to linearVelocity just makes it add up and move obscenely fast
show code
depends on what you're going for. honestly im not the best at this myself. but i think most people usually add to linearVelocity and then cap it on the required axis
rb.linearVelocity += movement; is what i was doing
what are you trying to achieve ?
im trying to move the object by movement every frame
i believe you would want something like this
if (Mathf.Abs(rb.linearVelocityX) < maxSpeed)
rb.AddForce(movement);
what you wrote will keep adding onto the velocity and potentially go on faster and faster forever as you do movement
yes i'm aware that's why i'm asking what to do
you can do AddForce as shown above, or use .linearVelocity but instead of += just assign
= instead
then we're back to the issue of overriding gravity though
i'll just do the above solution
then exclude the y in the linearVelocity
ok
if 3d
rb.linearVelocity = new Vector3(horizontalMove, rb.linearVelocity.y, verticalMove)
or
Vector3 velocity = rb.linearVelocity ; velocity.x = horizontalMove; rb.linearVelocity = velocity;
if you're on 2D you can simply assign rb.linearVelocityX = horizontal
ok thanks
Is it better to add RigidBody to the sprite rather than creating an object separately for it?
"it depends" but usually you'd actually wanna do the oppisite and have your visuals exist under the logic
Elaborate.
Well usually the "logic" that actually does stuff like a rigidbody would be the parent
and as the visuals are kinda a "reaction" to that logic, they would be parented under the logic as a child
So basically Empty -> RigidBody2D component in Empty -> Sprite in Empty -> Animator in Sprite?
Player gameobject has Rigidbody2D, ,Collider2D, PlayerMovement
Child GameObject has Sprite Renderer
Depending on your games structure you can also choose to put your Collider2D in the child gameobject
Quick question but with unity timeline, is it possible to mute and unmute track groups via scripting. Pretty much I'm just sorting the dialogue for my game where I have the audio and text in separate track groups, and want to mute and unmute specific track groups, that contain different audio clips in the timeline - depending on the player's dialogue option selected.
I've been looking at the API and I'm so confused
Is this applicable to 3D as well?
I mean having your Mesh Renderer on child object
Yep
Hey sorry, if you're not too busy, would you mind answering my question?
What I'm confused about is how to go about muting and unmuting track groups via scripting, like I know that trackasset refers to tracks in timeline but I was looking on unity forums and they have code going on about timelineasset, but TrackAsset doesn't look like it inherits from TimeLineAsset in Unity's API?
to clarify this is about audio right?
hmm i havent come across this track groups yet
both TrackAsset and TimelineAsset inherit from PlayableAsset
It looks like muted can be set
set this to true
sry i got a little brainrotten now 
currently i have a lobby UI , the UI will list out available rooms, because there will be many rooms, i had pooled the UI elements that display the room info , with unity iobjectpool
i have an option for players to display the amount of room info that they want , by 50/60/70/80/90/100 at a time , lets call it int maxQuery
one way the lobby UI works, is to clean out all existing element UI when player change their "maxQuery"
so , for cleaning the element UI , which is better
PoolManager.Instance.Clear(ObjectPoolType.SessionDetail);
AllRoomsAvailable.Clear();```
```cs
foreach (GameObject element in AllElement)
{
PoolManager.Instance.Release();
}```
or i dont need to clean out the maxQuery?
In the background, both essentially do the same thing. The first is clearer though, I'd use that.
if they did the same thing that will be easy , i afraid it will actually extinguish the object and the pool need to instantiate it again lol
ty 👍
So what I was trying to do was that I have the control and audio tracks in a group to represent each 'chunk' of the script. What I was trying to do was mute and unmute each of these groups through a script, depending on the player's option chosen, if that makes sense.
What I'm really struggling with is trying to understand how I need to access the tracks to mute them.
Let me know if I need to be more clear, soz.
At the moment I'm just trying to have it work with one dialogue option, because then I can just put it altogether after this and actually start building the game
I was thinking of doing it this way because if I have 3 choices per scene then I can just unmute and mute the groups accordingly.
hello
so i wanted to handle input
and although following the documentation
it used an outdated method
is there any source that uses the new input method
preferably a website or in text format
input system?
yes
Yep this is for Input Manager, the old one. In Unity 6 the default is Input System
if you want to learn about input system youll need to look for that keyword specifically
I have a problem that the player dashes only in right direction (therefore I have a code that should fix it in lines 62-66)
my script: https://gist.github.com/bielo1656/b295d27c7191ddebe652bb69e2fe0724#file-gistfile1-txt
the top if statements run.. thats fine.. (but then hwen u get down to crouching input it also runs... same frame..
so if ur not crouching.. its gonna go right back to 5,5,5
doesn't matter what ur horizontal input is
could do something like
if (horizontalInput > 0.01f)
facingDirection = 1f;
else if (horizontalInput < -0.01f)
facingDirection = -1f;```
and then use facing direction multiplied w/ ur X scale in the crouch method
or.. do all ur inputs together in a set of if elses
Hey, can I not get to see this list on the editor and add elements to it???
I was hoping I could
StatAttribute must be serializable
Can I ask a question: why do I have to multiply my X axis with my facing direction for crouching?
since crouching is just changing in the scale
or is it?
b/c its overwriting the X
ur horizontal makes it 5 or -5..
but then ur crouch overwrites it right back to 5
see both conditions are 5
soo.. it really doesnt matter what ur horizontal sets it to.. b/c u just overwrite it back to 5 anyway..
both the flip and crouch should probably just be modifying the relevant part instead of overwriting the whole thing
true.. thats another option ^
new Vector3(transform.localScale.x, 5, 5);
or new Vector3(transform.localScale.x, 2.2, 5); for the other condition
the entire Update() runs in a single frame.. (all the code).. u cant set 1 thing at the top.. and then something different at the bottom.. and expect it to show different results
if u walk thru ur code one step at a time you'll understand the issue...
pretend ur pressing Left and Crouching at teh same time.. then write down what the X of the local scale ends up as.. and what it should end up as
public GameObject Get(ObjectPoolType poolType, Transform parent)
{
GameObject obj = AllObjectPools[poolType].Instance.Get();
obj.transform.SetParent(parent,false);
return obj;
}```
```cs
public void Clear(ObjectPoolType poolType) => AllObjectPools[poolType].Instance.Clear();```
this is the get and clear function of my pool , somehow the clear function is not working tho
it can get object properly
release is also working
wdym by "not working"
when i call the "clear" function, all the object that spawned from the object pool should be released or destroyed right?
but its not
wait
yep its not clearing
I don't think it destroys any objects
it just makes the objects not associated with the pool anymore
ohhhh
Although I do think it should run your actionOnDestroy if you provided one when you constructed the pool
did you?
private GameObject CreatePoolObj() => Instantiate(Prefab);
private void OnGetPoolObj(GameObject poolObj) => poolObj.gameObject.SetActive(true);
private void OnReturnPoolObj(GameObject poolObj) => poolObj.gameObject.SetActive(false);
private void OnDestroyPoolObj(GameObject poolObj) => Destroy(poolObj);```
what about the line where you create the pool?
i do have the basic 4 functions
public IObjectPool<GameObject> Instance
{
get
{
if (constructedInstance == null)
{
constructedInstance = new ObjectPool<GameObject>(CreatePoolObj, OnGetPoolObj, OnReturnPoolObj, OnDestroyPoolObj, checkPool, DefaultPoolSize, MaxPoolSize);
}
return constructedInstance;
}
}```
ok yes this should destroy the objects theoretically
i have another version of object pool but its integrated with netcode
so the code are very different
i think so, but its not, i think i will double check
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://paste.mod.gg/ldoxyvaxpqzn/0
@wintry quarry this is the update function of the UI, here it spawns the element UI and remove it if necessary
A tool for sharing your source code with the world!
the get function is working
also the filter are properly populated
foreach (SessionDetail element in AllRoomsAvailable)
{
PoolManager.Instance.Release(ObjectPoolType.SessionDetail, element.gameObject);
}```
i just gonna loop over the gameobject instead...
it does work this way tho
guys am new to this can anyone tell me what should i do to learn about coding i wanna get to a professionel level to create my own game with my friends
any tips?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
is it all i need?
no
also see pinned resources in this channel
and docs, google, the forum will be very helpful as well
alright thank you
Guys. Should i keep continue writing in same c# file in unity or should i create another one? For exampld i made jumping mechanic for my character i gave it 2 jumping limit until it hits ground collision now i will code character WASD movement. Im not sure if i should continue from same c# file or create another
do iobjectpool has methods that can return all existing/active objects that it instantiated and not yet disposed(destroyed)?
not including released(inactive) objects
Each script should do one thing. How you define a "thing" is mostly up to you. Is jumping part of movement or is it a different action? That's up to you to decide.
This is the code. I guess i will write another c# code for WASD controls
!code
also just FYI but that last line of Update is not within the scope of the if statement (not that it really makes any difference in this case)
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
But it works
🤣
yes, i am aware.
Is there a limit inside update
Im trying to learn thank u for info
I will researxh
this question does not make a lot of sense. what do you mean by a "limit inside update"?
I will change the question and makr it clear. what should i do to fix it
Fix... what
i don't even know what you are asking, hence the reason i asked for clarification . . .
I was talking about this
Is there any issue on my code so i can fix it
Or is it fine
i mean, it's currently fine, but if you don't know how to include multiple lines inside the scope of an if statement, perhaps start by learning the basics of c#. there are beginner courses pinned in this channel
Are you having any problems with it
Code works fine inside game but i was curious if its written wrong
Yes i following them
the way you have formatted it, it seems you expect that last line to be included in the scope of the if statement (which is it not)
break goes out of the current "if", "for" etc right? so if i have 2 stacked ifs and i write "break;" in the inner one it would go back to the outer if?
This?
yes
Thanks
c# is not python. white space does not matter, just because that last line is at the same indentation as the one before it does not mean it is in the same scope
it seems like this is something you've discovered but not understood, given the duplicate condition
Thank u.
you should probably go through some beginner c# resources, there are some pinned in this channel
Yes i need to study abt if else again
Its good to see my mistakes and see what should i study again
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I will use one of these next time i post my code
Hi!
I don't know if this is more beginner code or not but I need help with a code snippet that make's a lot of sense in my head but is not working for some reason.
I'm trying to use the new input system to make my character sprint, but it is isn't sprinting. Help pls
https://paste.mod.gg/bjccxwwhtidw/0
A tool for sharing your source code with the world!
You don't do anything with m_speedWhileSprinting
oh wow, embarrassing. ty
hello guys, i try to code a 2d Top down view game and my kinematic character go througt object and d'ont car about it, thank you so much if someone can help me !!
my kinematic character go througt object and d'ont car about it
Yeah that's pretty much the definition of kinematic objects
working as expected
how i can do collision to dont allow going througt
can u explain i don't understand well
pls
what part are you confused by
i dont understand what i need to change else of kinematic to dynamic
Change your code so it sets the Rigidbody's linearVelocity instead of calling MovePosition
i change this so ?
movement.x = Input.GetAxisRaw("Horizontal"); // -1, 0 ou 1
movement.y = Input.GetAxisRaw("Vertical"); // -1, 0 ou 1
movement.Normalize();
okayyy
this
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
rb.linearVelocity = movement * movespeed;
if you're using Unity 2022 or less, its just .velocity
yeah I assumed you were on Unity 6
most recent version of unity are better ?
i'm pretty sure there is something else wrong but since yesterday i can't find it
it doesn't work with dynamic
wdym "it doesn't work with dynamic " ?

