#💻┃code-beginner
1 messages · Page 125 of 1
hm- quick question, but how complicated is creating a pathfinding system for a very simple 2D game?
Not that complicated, especially not if you have a tilemap already
oh, the game is top down, and only has . . three types of terrain
( road, plains, and forest ), and doesn't work of a tilemap system
I just want to make the system use the quickest route to move from A to B, with the roads increasing movement speed and forests decreasing it
thank you-
thanks as well-
why does this appear if my mesh does not have a rigidbody?
sounds like it probably does have a rigidbody. keep in mind that a parent object with a rigidbody still counts
the parent does have a rigidbody, but the game seems to work fine regardless
well that's exactly why you're getting that error message then
i made a small fix to remove the error message, it didn't affect the functionality at all it just made that annoying message go awat
datetime.now is bad anyway
user can just change phone date
like old methods in 2010 games 😄
better to get some server online date
also- is there a way to use OnTriggerEnter2D but only have it fire when interacting/entering a specific collider? ( i.e a collider of a specific name or something- )
put an if statement inside of OnTriggerEnter2D that checks that you are overlapping the thing you want to. it's recommended to use tags or check for a specific kind of component rather than relying on the name of the object though
why should I not rely on the name of the object?
Thx for the info
well for starters there will be no proper error messages if you've spelled it wrong. then there's also the fact that if you plan on creating clones of an object you have to also consider that its clones will have (Clone) appended to its name
because they can and will change
i have no tools either
I don't know if this a coding related issue but unity parameters are not reading the parameter that i set
or rather- how do I check what I am colliding with?
i get 644 warning and im not to sure what to do
What do the warnings say? Animator parameters are case-sensitive like most stuff, so Thing is not the same as thing
I get that but they are correct in my code
Like I want it optional and... Do you mean this? It doesn't work Idk why :(
they dont exist
Make sure you're referring to the correct Animator at runtime. Your variable may not have the value you think it has
im new so im not getting what you mean
You have a variable of type Animator in your code right?
that code is not even the class generating the error is it?
I see nothing there that would generate a null ref
Animator animator;
int direction = 1 // just refers back to the movement -1 for left 1 for right
void FixedUpdate()
{
if ()
{
animator.SetFloat("Move X", 0);
animator.SetFloat("Move Y", direction);
}
else
{
animator.SetFloat("Move X", direction);
animator.SetFloat("Move Y", 0);
}
}
You left off the line numbers. What are line 41 and 50
Ignoring the load of errors this would produce, you indeed have a variable of type Animator, called animator.
So where do you put a value into that variable? Do you drag-drop an object in the Inspector directly? Or are you using some kind of GetComponent<Animator>() in your code?
oh shit i forgot to inlcue that in the type up, but it's in void update with the ridigebody
im sick and having to force my self to write code
Post the whole class, unedited, here. If it's longer than 20 lines or so, use a paste website (see below)
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
using System.Collections;
using System.Collections.Generic;
using UnityEditor.U2D.Animation;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.Events;
public class EnemyController : MonoBehaviour
{
float timer;
int direction = 1;
Rigidbody2D rigidbody2d;
public float speed;
public bool vertical;
public float changeTime = 3.0f;
Animator animator;
void Start()
{
rigidbody2d = GetComponent<Rigidbody2D>();
timer = changeTime;
animator = GetComponent<Animator>();
}
void Update()
{
timer -= +Time.deltaTime;
if (timer < 0)
{
direction = -direction;
timer = changeTime;
}
if (vertical)
{
animator.SetFloat("Move X", 0);
animator.SetFloat("Move Y", direction);
}
else
{
animator.SetFloat("Move X", direction);
animator.SetFloat("Move Y", 0);
}
}
void FixedUpdate()
{
Vector2 position = rigidbody2d.position;
if (vertical)
{
position.y = position.y + Time.deltaTime * speed * direction; ;
}
else
{
position.x = position.x + Time.deltaTime * speed * direction; ;
}
rigidbody2d.MovePosition(position);
}
void OnCollisionEnter2D(Collision2D other)
{
RubyController player = other.gameObject.GetComponent<RubyController>();
if (player != null)
{
player.ChangeHealth(-1);
}
}
}
Okay this searches the game object this script is on for an Animator.
Make sure the script isn't attached to another object, with another animator.
Make sure there is only one Animator on the game object this script is attached to
okay i just put a 1 infront of the variable so im not referencing it in any other code
The variable was private so it was not visible to other code anyway (when you don't specify private or public or any other, it's assumed private)
extreme xhale
Can you go back to Unity for a second and in the search bar at the top of the Hierarchy, type t:EnemyController? This will filter out the Hierarchy so only objects that have your script are displayed. From there see if you didn't attach the script to another object by accident
hi thats my enemy's ai code
the enemy can go to destinations
play idle animations
but cant chase me
i think the problem is about raycast
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
how can i fix any advice? like how can i see my enemys raycast
Code block too large, use a paste website
i writed like ''cs but it says too long
Some users won't be able to see that embed
if only there were instructions for posting large code blocks
how should i send it
void Update()
{
Vector3 direction = (player.position - transform.position).normalized;
RaycastHit hit;
if (Physics.Raycast(transform.position + rayCastOffset, direction, out hit, sightDistance))
{
if (hit.collider.gameObject.tag == "Player")
{
walking = false;
StopCoroutine("stayIdle");
StopCoroutine("chaseRoutine");
StartCoroutine("chaseRoutine");
chasing = true;
}
}
it is the part of my code
how can i see the raycast
like gizmo or something
depending on your unity version you can either use the physics debugger to see it or you'll have to draw it with a Debug.DrawRay or something
i think im using 2022 or 2023 latest lts
latest lts is 2022. so you should be able to use the physics debugger for viewing your raycast
physics debugger ok
I want to show something like "PRESS [KEY] TO PICK UP" on the player's screen, but I don't know how to convert a keycode (for instance, KeyCode.E) into a string (which would be "E")
i am checking it tysm
KeyCode.E.ToString() - the ToString() method is available on everything
myKeyCode.ToString()
i figured it out
really? I thought that only worked for ints, floats, and all those. thanks! thanks also @wintry quarry
literally everything in C# is a System.Object, which is where ToString comes from. https://learn.microsoft.com/en-us/dotnet/api/system.object.tostring?view=net-8.0
Hey just got this error when I tried to load my project any fixes?
doesn't seem like a code issue
probably your scene file is corrupted somehow. Load it from a backup / version control version which worked
and yeah not a code issue
Okay, where can I access a backup?
have you backed up your project in any way?
did you make one? You tell us.
I didnt...
Then you are a bit out of luck. It's likely you'll need to recreate this scene from scratch
It's possible you could manually open the scene file and salvage it but not likely.
i tried to do with pyhsics debugger but i couldn't do that any advice
that's not very specific. what do you mean you "couldn't do that"?
you just open up the physics debug window, make sure that the queries option is enabled and look in scene view and you'll see it
First image: UpgradeText is null, you never check if it exists.
Second image: upgraderSkrypt is null, there is no check around it
vs not recognising some stuff, how to fix?
!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
• Other/None
Ok ty
Im in a ooga booga brain where i just do and no think
void Update()
{
Vector3 direction = (player.position - transform.position).normalized;
RaycastHit hit;
Debug.DrawRay(transform.position + rayCastOffset, direction * sightDistance, Color.green);
if (Physics.Raycast(transform.position + rayCastOffset, direction, out hit, sightDistance))
{
if (hit.collider.gameObject.tag == "Player")
{
walking = false;
StopCoroutine("stayIdle");
StopCoroutine("chaseRoutine");
StartCoroutine("chaseRoutine");
chasing = true;
}
}
i added this Debug.DrawRay but it doesn't shown
do you have gizmos enabled?
then either that code is not running or the raycast is not where you expect it to be. or sightDistance is 0
code is runing i think because the snowman moving
nothing in that code you've shown moves it
um i will check the 2 other option the sightdistance and raycast position thing
its a long code but i can't post bcs of limit
if only there were instructions for posting large blocks of !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Just for good measure since they skipped it on the first one:
Post the link!
sight distance setted 15
your StopCoroutines are incorrect
Coroutine cor = StartCoroutine(...);
StopCoroutine(cor);
Hey guys I need help on playing multiple particle systems simultaneously after a grenade explodes
i gave you three reasons why you wouldn't be seeing your Debug.DrawRay. if sightDistances is not 0 then check the other reasons
I don't know how to do that through code
How do you exactly play particle systems
Is it some variable I'm unaware of that I can assign and then play in the grenade code?
so unity you got some explaining to do as in the check scrips section this change DOESNT EXIST (on the new vector2 exist the second line is what im refering too)
omg man you are right i changed the color of it to red to see where it is and it is here lmao
What doesn't exist?
what is the "check scrips section"?
position = position
in the guide they have a check script section to make sure u "have" what they have
type of this its usually oh i missed something or i dont get something
what is the context of your question? Presumably there is some variable named position from earlier.
Or maybe they made a mistake and it's supposed to be transform.position
so then most likely the object your script is on is not the same as the NavMeshAgent or it is not a child of the NavMeshAgent.
if it relies on the position of the navmeshagent so either use the NavMeshAgent's position or attach this component to that same object
the new one is the move + speed but its the same
which guide?
tysm sensei. I will immediately implement what you say.
maybe link to the section you're referring to?
Guys, I really need help on how to play a particle system through code
im about to get into that
but for 3d or 2d is a question too
that makes no difference, there is not a 2d particle system component because you can just use the ParticleSystem component
It just gave me a sample GUI script
I have a game object holding all the particle systems I want to play
Does it work on empty game objects that hold particle system children?
I'm new to this, sorry
wdym "it"? ChatGPT?
you play ParticleSystems with .Play:
https://docs.unity3d.com/ScriptReference/ParticleSystem.Play.html
If you want to play multiple particle systems, you'll need to call Play on each one of them
If you have them all in a list you can loop over the list and call Play on each one.
Oh alright
AH alright
Thank you
Again, my apologies if it was a stupid question
I'm gonna guess the docs also mention how to control the system such as pausing and stopping the systems, right?
of course, look through the docs for ParticleSystem, all that stuff is in there
Alright I'll look into it
If my English is flawed it's because I'm working on this project late at night so I apologize if my sleepiness caused any misunderstanding
if you have followed all of the instructions then close your IDE, regenerate project files, and restart it
then you've likely missed a step
It's easier to configure VS than VSC
really gone thru it 3 times
what IDE are you using
VS2022
do you have the unity workload installed?
now show your external tools settings
screenshot your entire IDE with a script open and the solution explorer visible
Why is this not working? I can't modify the value:
public class StatModifierItemData : ScriptableObject, IStatModifierItemData
{
private float _modifierValue;
public float modifierValue
{
get => _modifierValue;
set => _modifierValue = modifierValue;
}
public virtual void Init() { }
public float GetModifierStatValue()
{
return _modifierValue;
}
}
public class HealthBoosterData : StatModifierItemData
{
[SerializeField]
public float boostAmount;
public override void Init()
{
Debug.Log("Boost amount is " + boostAmount); // 500
Debug.Log("modifierValue is " + modifierValue); // 0
base.modifierValue = boostAmount;
Debug.Log("modifierValue is now " + modifierValue); // STILL 0
}
}
Guys, I can't insert my particle system in the inspector
What type is the field?
right click the Assembly-CSharp solution and select the reload with dependencies option
set => _modifierValue = value;
do you have script errors, check Console
Show what you are dragging in
And what nav is saying is ANY compiler errors, even unrelated
all fine?
Don't multiply mouse input by deltaTime
@languid spireOh I see, thanks
something while but i can ctrl click them
show vid
don't multiply mouse input by deltaTime, it's already frame rate independent so by multiplying it by deltaTime you end up with stuttery camera controls
really copied from pastebit just to look at the synthax xd
okok thank you
I have a function on a singleton, when its called by another script like this is it creating an instance of that function or does that only run the function on the singletons object? If so how could I instead use an instance of the function.
since Im running into a problem where if two people cast at the same time it mixes up the stats
you can't drag scene objects onto prefabs
doubt it
Should I use public Gamobject
only if the object in the scene was a prefab to begin with
I think you could drag it in then
just use 1 reference to the main VFX object
make a prefab out of that
and spawn VFX object
What if you unpack it?
It's no longer a prefab
what ur doing now makes no sense anyway
the script is already on the flashbang for example you can drag them within prefab editor
I just put 3 particle systems and I want to play them before the grenade explodes
Open the Prefab in context mode and drag them in 🤷♂️
why you need all three I have no clue. They could all just drop a prefab down and maybe pool that, they could set to Play On Awake
I followed a tutorial on making an explosion effect
I made one for the explosion, the other for the smoke, and another for the trails
All together they make one explosion effect from 3 systems
I get it
I'm sorry if I'm being obnoxious but may you please recommend a better way to handle this?
VFX can just be a prefab is what i was saying
did you make prefab enable all 3 particles Play ON Awake?
Elaborate
Drag it into the project window.
Drag the asset from the project window (not hierarchy) to the fields
Alright
is this thing enabled
so you dont have to manually call emit?
Done
alr so just need to change 3 ParticleSystem fields into 1 GameObject/Transform
Now I have it on my project window and hierarchy
then do Instantiate(vfxPrefab, etc..)
should I switch from vs code to visual studio or it doesn't make much diffirence?
yeah its a prefab now
drag the one in the Project tab (hopefully you deleted the unnecessary one in the scene..)
Yeah I did
I'll make an instance to the one on the project tab
Oh!
I get it now!
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Since the systems play on awake, every time there is a new instance of the system, it plays the systems automatically.
Thank you for your help
why doesn't my mouse hover event work but my on click one does?
https://hastebin.com/share/eyorewibex.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you linked empty hastebin
my bad
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you are not implementting IPointerEnterHandler, only IPointerClickHandler
oh okay that makes sense. thank you!
is there a way to implement all IPointer handlers at once?
I guess you could write your own interface which implements all of them
seems silly though
you can also use the EventTrigger component instead of implementing the interfaces
alright, thanks!
Is there any way to see small textures, bigger?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
please I need help, the object I want to instantiate instatiates twice every time
Ex: first 1, then 2, then 4, then 8...
Is the stopper component inside the _Stopper object?
I put it in the prefab
So the object that you want to instantiate has the component that instantiates?
While not directly a code question, I have an assignment and I was wondering if anyone could provide some insight
One of the requirements was
Your implementation should allow the saving and loading of game state data from the selected storage types (In-memory, PlayerPrefs).
Your design should allow the implementation of new storage types (for example: Json file, network url) of game state data, without modifying your existing solution
I know how to implement those storage types, the part thats confusing me is the last line
How do you make a storage type without modifying the existing solution
seems like a weird requirement
yes
They want you to separate the serialization of the data from saving it that's all, which is a really good requirement.
xRotation -= mouseY;
oh alright, that makes sense, thanks!
Okay so what's happening is that every time you instantiate the object, a new object with the component that instantiates is there, and that new object will start instantiating more objects, and more and more. You have to move that component outside the object that is being instantiated
Oh my god how cant I have seen it
XD we all have been there
no problem!
What would you like to understand from there? What I see is that the xRotation gets mouseY removed every time it moves. Mouse Y is a value that gets to 1 when the mouse moves, and 0 when it has stoped
why am i subtracting mouseY?
If you look at the axis, xRotation would be rotating around the X axis, and therefore the aparent vertical rotation (looking up and down is rotating through the X axis)
What would make sense to you?
because the top left of the screen is usually 0 0 in screenspace IIRC, so increasing mouse y actually means moving your mouse DOWN. So you subtract to invert that
nono i know that just dont get why X rotation with Y
Look at the axis I sent (or also in unity) and you will see that the axis where the rotation should be applied is X
because rotating around the x axis is how you tilt "up and down"
See diagram here
it's a rotation around the axis
You can also create a new gameobject(cube) and rotate the X value on the transform, and you will see how it goes up to down
ye i thought x was horizontal like in math
x is horizontal
x is horizontal
rotating around the horizontal axis results in "looking up and down"
exactly
No problem!
thank you sorry for my stupid a** xd
im gonna bump this, im stupid myself
(alttough im starting to thing that, unless i have a custom editor im not sure how im gonna do that, maybe there's a hidden button somewhere?)
This isn't really a code question
Try maybe #💻┃unity-talk ?
Not sure if it fits #🖼️┃2d-tools or #🔀┃art-asset-workflow
Guys, how can I make sure that when the scene loads the object that uses the transform of my player saves that transform from being destroyed?
DontDestroyOnLoad prob
Help With Camera States
is it common to do a DontDestroyOnLoad to the player?
Oh, really? thanks
depends what your exact needs are too
the thing is there is an object that instantiates according to the player´s transform. But when I reload the scene, that association breaks
do you not have a way to find player at runtime ? also some games don't even delete the player they just reset and respawn the same one
Will this make what I hope?
private Script1 my_Script1;
private Script2 my_Script2;
private void Start()
{
my_Script1.GetComponent<Script1>();
my_Script2.GetComponent<Script2>();
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "PlayerCollider")
{
my_Script1.enabled = false;
my_Script2.enabled = false;
}
}
}
I want to disable two scripts what are componments of a GameObjekt.
Do I will reach those Scripts like this or will this disable the entire GameObject?
I want that everytime the player dies, it spawns in teh beggining of the road(it is a race-type game)
Ye I know, tbh no point in destroying it
Ok, thanks a lot bro
From the magical world of dumb questions, how can I prevent two layers from colliding with each other in 2D? I've unticked the interaction in the Project Settings > Physics > Layer Collision Matrix, but my character is still able to stand on top of platforms that should now be non-colliding... (Player / OneWayPlatforms)
depends on the purpose
if you disable whole object any scripts stop working
not code question
The purpose is to disable those 2 scripts in a GameObjekt, without disabling the Gameobjekt itself.
also for 2D its the Physics2D section
Fair, apologies @rich adder .
but when I keep the player it is still there??
so do that lol
2d has its own settings
Thanks @wintry quarry . (facepalm)
why is everything white, I cant tell whats goin on
just a simulation
put some color on the player ?
anyway whats the problem ? if you put DDOl then you can't keep one in the scene already
or make a singleton
I'm heading over to #⚛️┃physics, but it's worth noting that changing the setting in the 2D Layer Collision Matrix doesn't seem to have done anything either. =/
make sure you set the layers correctly on each collider
and if I add the DDOL it still destroys that relation
I bought the complete c# course from Gamedev tv , but before starting the course I just want to know , in playmaker we use states to make our games and in those states we have stuff like "trigger event,float compare,translate,playsound,send global event etc" and this usually goes 1 by 1 but when i see c# code they use update or start and i never seen those in playmaker, lets say i triggered a event by pressing "Space key" and it did the code inside that if state, does it stay in that state or it just resets,if it does how does people make a story game
I was using playmaker a visual coding addon for 3 years and now I made the choice to switch to c#.
you prb used it wrong. and I told you what you should do instead
Just watch the course
transform.root
transform.root
use links for large code
Can you explain me how I can do that please ?
I tryed and it doesn´t work
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Thanks mate
tried what? what are you talking about exactly
the DDOL
Then you did it wrong
actually nvm it will still break
Hello! I have an hard time figuring out why my jump functionlity in my program doesn't work. Can someone help me please? I've tried different thing but I can't figure it out. Thx!
https://gdl.space/avuvayunus.cs
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
@rich adder Just to check... I shouldn't have to change Layer Overrides in CompositeCollider2Ds or TilemapCollider2Ds or Rigidbody2Ds, no? My assumption is that changing the matrix in the Project Settings should cover that. I also have PlatformEffector2D on the tilemap, which I suspect is the cause of this issue - does that make more sense?
hm yeah you would have to put it on the thing that has player reference too
the problem is that whenever I use it, then every time the scene loads not only does the player generate another, but also the relation breaks anyway
yes mate I can read
Or if you have only 1 player, then make him a singleton and reference him everytime you need
Many approaches
Pick one
what should i put in the code exactly
C# code
inside Start of your thing that u dont want break reference
myreference = GameManager.Instance.Player
I don't know if the link works, tell me if it works pls
Hi, why is my game view going to pause mode automatically whenever I start the game?
no the one on the gameobject
you prob have Error Pause
and a console error
is the script even running ?
yes
how you test?
What do you mean ?
ye unity remote surely thats not an issue
you're referencing Scene Objects on a DDOL..
you can't do that
it wil break
it was the issue 😭
Destroy(inventoryParent.transform.GetChild(0));
in the editor it says Calling Destroy or DestroyImmediate on a transform is not allowed.
then what should I do
sorry I dont understadn+
.gameObject ?
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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 don't really know what you mean. But I'm starting my game then I press run and jump while grounded and the jump "works" but not as intended. My character teleport to the location and fall really fast. I want it to jump like irl
Your gameManager is in a completely different scene because of DDOl
you cannot keep reference between difference scenes
oh okay so
Hi this is my Start() Function and I was wondering whether this is too much precomputation to happen in start. I think its like 2 nested for loops with like vector calculationshttps://hastebin.com/share/ogutuqoham.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I have no idea about new input system sorry.
maybe try
#🖱️┃input-system
Hey ! I want to get the deltaRotation of an object by doig this : cs deltaRotation = deltaRotation - transform.rotation;
where delta rotation is Quaternion but there is an error because i can't use an operator to it. I don't know how to do
🥲
The problem is the CharacterController not the new input system. When I press space bar it jump no problem on that. but I think it's the logic behind the jump
you can't add/subtract quaternions
Still can't help me ?
i can change the unity of it ? to rad for exemple ?
I haven't used new input system much to know sorry
how do you know its character controller
i'm dumb mb, i forgot the doc
thanks
Because I'm using a CharacterController to Move my character. My character move but not as intended, so by logic it's the CharacterController logic for the jump in my Update function that is wrong
I guess
give it some speed
idk what "not working as intended" means
Debug.Log your values
I have this cloud particle system thing and I want to display it like all across the bottom of my game
how would I do that?
I explained it earlier but I'm gonna explain it more clearly sorry. My code make the character teleport to the variable "jumpHeight" then the gravity do it's thing and the character fall. I don't want that, I want my character to jump like in real life then fall.
I tried += instead of =. I tried Mathf.sqrt(-2f * gravity * jumpHeight) for initial velocity but it doesn't work
this has example
probably. cause it works fine
the only issue is that the character controller grounded bool sucks
it only works while you move
is better to make grounded check with CheckSphere
Should I make an "isGrounded" variable myself with a raycast ?
I changed "direction.y = jumpHeight;" for "direction.y = Mathf.Sqrt(-3.0f * gravity * jumpHeight); "
And it still doesn't work. I have to put like jumpHeight = 200; to see something happen and what happen is just my character teleport instantly, then fall normally
private void Update()
{
characterSpeed = isRunning && _controller.isGrounded ? playerRunningSpeed : playerWalkingSpeed;
float xMoveValue = playerInputActions.GroundedGameplay.Movement.ReadValue<Vector2>().x * characterSpeed;
float zMoveValue = playerInputActions.GroundedGameplay.Movement.ReadValue<Vector2>().y * characterSpeed;
direction = new(xMoveValue, 0f, zMoveValue);
if(_controller.isGrounded && isJumping && isRunning)
{
direction.y += Mathf.Sqrt(-3.0f * gravity * jumpHeight);
}
direction.y += gravity;
_controller.Move(Time.deltaTime * direction);
}
Hey guys, sorry I'm not so active on this forum but I'd like some point of view on a solution to a problem I have,
I instantiate an object which is essentially just a skinned mesh renderer and a rigidbody at a specific place using a parent transform. The object is then moved by an animation and it moves relative to the character I'm animating (drawing an arrow from a quiver if you want context)
I want to have a rigidbody so I can apply a force to the arrow when the string gets released, but if I add a rigidbody, the arrow gets "stuck" and does not follow my animation.
Using isKinematic won't work, or at least I did not find a solution using it. (I have no issues of placement of the arrow when there is no rigidbody btw)
I used ChatGPT so I would not waste you guys some time, and the AI found a solution : storing the rigidbody values, Destroy the rigidbody, then add a new rigidbody and add the destroyed rigidbody values.
Is that fine? Am I missing something easier ?
Thanks a lot if you read me,
OP7
show unpector for player
whats gravity set to
-9.8f
Is there a small and easy way to set all arrays to "true" without changing every single array to true with a for or while loop?
No
@rich adder
Pretty sure the problem was the PlatformEffector2D, but I'm open to other suggestions.
I really don't understand what I'm doing wrong, I'm new to Unity so it's probably something stupid
yeah probably , I don't work in 2D often
Very reasonable. I'm doing this for a friend, normally don't touch 2D.
debugging is the first thing you should learn
How can I do that ?
I found something helpful. If you click the three dots in the top right corner of the gameObject inspector you want to debug there is a "debug" option that shows you all the variables
yeah but that doesn't tell you everything, just the basic fields
Ok I see
Hello, new to the discord, I have been able to debug pretty much anything else so far in my project, however i have been stuck on this for almost a week so I think I need some help. My player will move correctly, won't be able to move while dead; however, if the player dies while moving, will slide off the screen into nothingness, resetting velocity, removing materials, and many other things haven't worked.
I am using a CharacterController not a rigidbody
show !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
Yo ! You should put your code so that people can help you 👍
Okay, like I said new to the discord so Iwasn't sure where to post it and not spam the chat,
np
Thank you!
you send new code?
I'm searching the problem, I'll come back to you if I'm stuck 👍
Hello there. Let's say I have enum with 3 options. How do I check which option is assigned thru if statement?
public enum ExpirePoint { BATTLE_END, TURN_START, TURN_END }
if (ExpirePoint == ???){}
if(myEnumField == ExpirePoint .BATTLE_END)
//its battleEnd```
where do I take myEnum? 😄
well, you need a field for an ExpirePoint
you just created the enum , never actually use it anywhere
yes, so that's also is a part of a question... so I make the script that will check what this exact enum states... what do I add to the script so it can actually access that created enum? I guess instead of asking I just have to see some examples from code that I have that uses enums... brb 🙂
a ye, okay okay
thank you
if(currentState == TurnState.Dead)
//etc
yeap, exactly. THank you very much
if you need to check if any of those is true at once, then you can do a switch instead of a chained else if
do i need to learn c# for unity?
I will have 3 options only so I guess if, else if, else will be enough
100%
ouch
its not that diffcult
idk typescript tbh
html is considered a programming language?
its just javascript with type-enforcement
i...think so
not really
you got this for sure
gotta start somewhere
How can i create a script that shortens my item dropping distance, when a wall is directly in front of the player? I'm having a issue with the player being able to drop items into walls.
raycasts
raycasthit.distance you can see how close something is in your throwing
just make distance shorter than that for throw
okay thanks
What's the basic difference between arrays and lists? I mean what would be the NO GO for each of those? List is more flexible I guess? If you remove certain thing from the list, nothing breaks, right? And if one removes some link from array, it can cause troubles?
arrays size cannot be modified without creating a new array
lists can
simple as that
Does anyone have example of large project structure? It is becoming unbearable
oh, okay, that's it. So if I want some magic attack to have few status effects that it will apply, I better use array for those status effects, right? Those will be fixed and won't be modified anywhere at all
if the size is fixed use array and replace the item, if it grows / shrinks use list
okay, thank you 🙂
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
@rich adder I still don't know why the bug happened but at least it's fixed. What I did is I created a new Vector3 = Vector3.zero and to this Vector3.y I do all my magic and then do a different _controller.Move on this Vector3. And doing it like that make it work ✋ 🤠 🤚
Can you explain to me the thing about the sphere you talk about ? As you said isGrounded kinda suck because I need to move. What is the work around ?
private bool Grounded()
{
return Physics.CheckSphere(transform.position + groundCheckOffset, groundCheckRadius, groundLayers, QueryTriggerInteraction.Ignore);
}
private void OnDrawGizmos()
{
if (!debugGizmosEnabled) return;
if (cc == null) return;
var color = Grounded() ? Color.green : Color.red;
Gizmos.color = color;
Gizmos.DrawSphere(transform.position + groundCheckOffset, groundCheckRadius);
}```
👽
its a pretty basic function
https://docs.unity3d.com/ScriptReference/Physics.CheckSphere.html
What use a Sphere and not a raycast ? (I don't know what is CheckSphere I just suppose it's a raycast sphere)
I know xD, just wanted the explication not the function xD
because a line wouldnt make sense
Why ? I don't get it
the CC is a capsule
only a sphere makes much sense
you can use w/e shape ofc
What is w/e ?
whatever lol
Ok thanks (not my first language sorry)
Thanks for the explanation then, I'll do that !
Hello everyone, have a sort of annoying minor issue I can't seem to find the solution to.
I get the "domain reload" popup every time I edit and save a script, and it prevents me from alt-tabbing back to unity and is generally annoying. Quick google says to turn off auto-refresh in preferances, I remember this working briefly but has since stopped working.
The way of Project settings --> Enter Play Mode Settings --> Enable Domain Reload has no effect either.
Am I missing something obvious? Or is this just something to deal with? Thanks.
I think you're thinking of compilation reload
Yes, I think so
Is there a way to turn it off, or at least do it without the annoying popup window that prevents alt-tab (in the background?)
Disabling auto refresh is what you need.
Enter play mode settings only affect entering play mode.
Yes.
Was it not in General tab..?🤔
It doesn't seem like compilation though. It says scene hierarchy repaint.
Don't think so haha
If it helps, it does several things, domain reload too (as if I know what that is)
I guess it was moved there in the recent versions.
Ah okay. It seems like the setting is not taking effect then.🤔
Try resetting it to something else and back to disabled. And if that doesn't help, restart the editor.
Am I doing something wrong when rendering Gizmos? Here is my code but I don't see it anywhere in the scene view. I tried using gizmos for the first time to see why my Physics2D.OverlapCircleAll was not working. I even set the radius to 100f and the PlanetMask to "Everything". Any ideas?
Gizmos code:
void OnDrawGizmosSelect()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(Vector2.zero ,1f);
}
Overlap Code
Collider2D[] colliders = Physics2D.OverlapCircleAll(Vector2.zero, 10 , PlanetMask);
Debug.Log(colliders.Length.ToString() + " Planets found");
what happen if you make something like this?
[SerializeField] public int Numbers;
Is SerializeField usefull on a public variable?
go through this to troubleshoot your overlapcircle: https://unity.huh.how/physics-queries
No, it is not
Public is already serialized
What about the Gizmos though?
public variables are automatically serialized so it won’t do anything
do you have the object selected and the component unfolded in the inspector?
so, its useless in combination of public.
I think I found it-- I was hitting the x in the top-right instead of using the "exit" function under file, I guess one reloads the settings properly. Thanks!
what do you mean unfolded?
i mean, is the component not folded in the inspector
also do you even have gizmos enabled?
it appears I am not familiar with the term "folded" when it comes to gameobjects in the inspector.
and yes I have gizmos enabled
you know how every component has a little > arrow next to its name and you can click it and it hides the component as if it were some sort of foldout display?
not folded
folded
but it is selected in the hierarchy, yes?
yes
but I managed to find the OverlapCircleAll() issue
so there is no need to solve the gizmos thing anymore
jk lol, it has started reloading domain again :(
i'm pretty sure it has to reload the domain when you compile 🤔
Yeah, but it shouldn't compile on alt tab
it's entering play mode that domain reloads can be disabled for
entering the editor again is what is triggering the compile/domain reload
no no, I just mean the popup window prevents alt-tab to unity, its a windows thing
It will of course. It's blocking the main thread
is it just cope or get a second monitor lol
The question is wether it happens after alt tabing from your ide
I don't think so, is the reload just a thing to deal with?
Yes. That's what needs to happen on recompiling your scripts(to apply the changes that you made)
you might be able to turn off the auto refresh, of course if that stops it from reloading the domain, that means its also not recompiling so you'd have to trigger that manually
nahh mate id need a physics degree for this
pardon, one question
I did this
insteaad of this
but theres some input lag
I don't think that would cause input lag on it's own. Did you change anything else?
i didnt
Can you show some more of the code?
And, if you switch to the old lines, does the input lag go away?
trying rn
I have no idea why changing those two lines would cause input lag. And can you clarify: By lag do you mean a delay, or unexpected rotation?
little input lag + view lagging a bit more
i think its because it first moves the player object and then the camera so the camera gets rotate a bit later
can this be it?
The order does not matter, it's in the same update function so they will be done within the same frame.
Is anything else modifying either rotation?
wdym
Do you have another script that interacts with either object?
There's really nothing that should be creating lag then. Are you absolutely sure you notice a delay? And this delay goes away when using the one line instead?
Mixing up rigidbody and character controller is a terrible idea and would cause more issues than just jiterring.
idk lol, thank you Frog!
who are you talking to sorry?
i think your issue is the only one being discussed now.
there was a post before but i did not use any rigidbody
so im raycasting and my debug ray works as intended but the actual one doesnt? see attached any help is appreciated
private void FixedUpdate()
{
Debug.DrawRay(transform.position, transform.forward * maxDistance, Color.green);
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, maxDistance))
{
Debug.Log("Raycast hit: " + hit.collider.gameObject.name);
if (hit.collider.gameObject.CompareTag("screen"))
{
Debug.Log("Screen detected");
script.playerLooking = true;
}
}
}
How do i fix rigidbody jitter?
enable interpolation on the Rigidbody
Oh, okay. Misread the code. I thought you were setting rb velocity.
np
what do you men by "doesn't work"? What is going wrong?
I did, and its mostly when moving sideways.
you'd have to show the code etc
the actual raycaster in the if statement isnt detecting anything and its not displayed in editor
then there is no collider there
This is it ```targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
Vector3 MoveVector = transform.TransformDirection(Vector3.ClampMagnitude(targetVelocity, 1f) * playerSpeed);
rb.velocity = new Vector3(MoveVector.x, rb.velocity.y, MoveVector.z);```
nothing here will cause jitter
are you sure it is the rigidbody that is jittering and not perhaps the camera?
nnno its just not raycasting and i dont know why, it has a collider
I'm using a camera as a child of this object, could that cause issues?
wdym "it's not rycasting"? Clearly it's raycasting since the ray is being drawn i.e. the code is running
show the collider
the debug ray is being drawn, not the actual one. heres collider
you have an error in your console
what is it
also what is being printed?
you're also hiding your regular logs
Would following this object using script work?
Yes but it means the code is running, so the raycast is happening
unassigned reference from player controller
cinemachine will be better
didnt notice this holdon
where? In this code?
other code but it doesnt effect anything so im going to fix it later
Would it be hard to replace my current setup?
i think i found the issue tho
no, it's actually fairly easy to use. check the docs pinned in #🎥┃cinemachine to get started
aii i figured it out there was a collider in the way, thx for the help
Okay i did it, and suprisingly it works easily, only problem is that my movement script moves x and z, regardless of what way i'm lookiong.
i don't know what you mean by that
as u guys see, im dealing with server error responses , i think a dictionary would be better than bunch of if in this case?
u guys think 658 part can be merged into the dictionary as well?
This dictionary should not be allocated every time you call the method if it's not changing every time, that's the only thing I have to add
Doesn't seem constant, you are declaring it in a method
Make it static?
In the class
this is dictionary<string,action>()
but the action in dictionary contains another action
which is declared inside a function
so i cant pull it out
aight
static class
maybe that will do
oh ok
@nimble apex And yeah you can put 658 into the dictionary too, just pass a method or put the if-statement into the lambda
oh nice
btw cant pull it out, unless this dictionary is being put into a separate class, some variables are declared inside the function its in rn
u cant make dictionary static as local collection right?
Nah, you gotta restructure it a bit I think
inside the dictionary, their action will include the two actions above
wait
i can
i just need to make those two as a function
nice ty
i think this needs to be put into static class
the problem my team facing now, is this dictionary will need to be used under various scene controlling scripts, like from different scene
the script that i used now is from one of the controlling scripts
if i make it to a static class i dont need to put the dictionary into 10+ scene controlling scripts right?
Would anyone know what I should look up if I wanted to splice two animations together if the animated object hits a collider? I know how to do the collider part, just don't know where to start with splicing animations
alright, I didn't know if this was a scripting thing or an animation thing, thanks
eventually my dictionary is finished , ty👍
unity can do indexer on dictionary to add a new set of stuff if it doesnt exist in dictionary?
anyway this is my call part to the dictionary
yep its tidier lol
I opened unity and got hit with these errors. I think LinearOffset got unassigned somehow but I can not reassign it as the script is greyed out
there are compile errors
so your script wont be compiled
hey guys i have a quick question
"PlayerTransform = GameObject.FindGameObjectWithTag ("Player").transform;" is a valid line of code. however
"PlayerTransform = GameObject.FindGameObjectsWithTag ("Player").transform;" is not?
Because the second returns an array of objects
GameObject.FindGameObjectsWithTag ("Player").transform
guys i need a bit of help with my procedural generation script
u cannot just refer to transform of a collection of game objects
u need to make another collection , loop thru and add up each transform of the game objects
!code
format the code as inline code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
oh
cuz it kinda spawns slightly at the edge, how can i prevent this
i wonder how the -5.03, 0.57 0.09 come up
the rotation is correct btw by they overlap, that means the spawn position is wrong
and please dont Find() every time
yeah, the spawn position is weird
if i remove all the adding and stuff, it'll like be going down for some reason
like a stair case a little
ok i removed those things, it worked ish, but it goes down and the rooms are like overalping with the previous room
Hate the classic box dungeons? I re-imagined the classic Minecraft Dungeons using jigsaw blocks to add custom structures to Minecraft with no mods using datapacks! And this video is a complete guide from the basic concepts to the technical details of how to make custom structures to Minecraft for yourself!
Data Pack Template - https://drive.go...
youo can watch this
alright thanks
u were right man, i changed the origin positions and it started to work!
(at least for the rooms that are straight
Ok now everything works now thanks
I know that but it says GameObject doesnt contain a definition of size when it should
https://docs.unity3d.com/ScriptReference/GameObject.html
search "size" and "Size" by ctrl f
Is there a way I can relate a variable to another set variable?
Here's the code that I tried:
Variables I am trying to relate it to
or you mean transform? though it is still not called as size but scale
gameObject.transform.scale = new Vector3(xSize, ySize, zSize)
@sacred orbit is your ide configured?
I honestly don't know how to, I just started with Visual Studio like 10 days ago
!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
• Other/None
idk how you install your VS so pick the link yourself
alright I did it
anyways, is relating a Variable to another set Variable possible?
I could use switch but I would like to be as light with the resource use as possible
What do you mean by that? Switch statements are not heavy on anything
oh really?
maybe if you have a switch of 50 things you're checking every update
It's just this would be in Update() so I thought running a switch statement every frame wouldn't be great
More like a switch of 10,000 things, as in, running 10,000x
ok thank you
That still wont make a dent 🤣
well, for a single instance I guessss
I am really new to unity and c# so thiuss is good to know
I've been a bit too worried about lag then
Don't consider yourself with performance until you're actually experiencing it and know how it works and how to resolve it
just speculatively avoiding things is a great way to get nowhere and write bad code in the process
Im not sure what you are trying to do. You want heldItem to be storage1 2 or 3 ?
Whenever you're numbering variables you probably should just be using an array or list instead
storagenGO is storage number game object, just swapping between 3 gameobjects for an inventory system
but my problem is solved, thanks
Huh did they change it because I havent changed this code in months
wait for some reason I moved the declaration of linearoffset (a box collider) into a line of declarations of gameobjects
no clue how I did that
or why at least
my visual studio no longer autofills variable types; what settings did I change that I need to unchange?
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
If it is already configured, you may just need to restart it
I am a complete beginner to C# so I just wanna ask
Is there like a library or list or something so that I can know the properties that I need to call when I want to script things
I've worked with Luau before, used to do Roblox Studio and I want to move to Unity, so I think I can wrap my head around the basics of C# I just need to know how people are able to know like Variable.Instance.This.That.Etc
Is it just learning and memorisation or is there a cohesive list of properties that you can change/script with
!docs
ah, thank you
I already had it configured and restarted; it was already configured in the past and has suggested variable types but now doesn't
I have this paddle boat set up and i have the paddle attached to the mouse, im just unsure of how to properly add thrust to the boat when the mouse is down/paddle is being used. How should I go about adding the movement?
Also note that a configured !ide tells you the members of something as you type
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
• Other/None
I have mine configured and it is listed under external tools but still does not show me anything unity related
You've definitely got the Unity workload installed in VS?
No idea then. I use 
damn
Try:
- If you have compiler errors, if possible comment out those files so Unity can compile code.
- Ensure the Visual Studio Editor package is installed and updated in UPM (com.unity.ide.visualstudio).
- Regenerate project files via Unity.
- Close VS.
- Select regenerate project files in Edit > Preferences > External Tools.
- Reopen VS via Assets > Open C# Project.
- Regenerate project files via VS.
- If an assembly in the Solution Explorer is marked as (incompatible), right-click it and select reload with dependencies.
- Restart your computer.
regenerating via VS worked. Thanks!
what are the practical usages of generics and polymorphism in C#?
Generics allow you to write shared code once for multiple different types
system.collections.generic
I find generics pretty useful with data coupling when it comes to scriptable objects
Polymorphism, requires a object-oriented approach so it's less useful; but storing similar things in the same place while having them run different implementations
I'm trying to make conways game of life in Unity.
Is there a way to make these tilemap lines visible in the game view?
It looks weird without the lines
if not, then consider drawing via GL Lines
thanks, I will look that up
Could maybe try LineRender as well, but I've not really used it for a large amount of lines before
would require a GO for each so extra overhead
you can draw line this, but no one can understand your code after 2 months
(just fetch the eular path or solving chinese postman problem)
I have one example for a save system if you want to save different objects but only use 1 method, generic is very good to keep method modular
Could someone help me figure out why this script is doing nothing? It is supposed to drag the image with my mouse but its not moving, the event is also not even getting called?
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class DraggableItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("Begin Drag");
}
public void OnDrag(PointerEventData eventData)
{
Debug.Log("Dragging");
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("End Drag");
}
}
The script is attached to each image
im going to bed but any help would be read and appreciated in a few hours
idk about the events but I don't think transform.position = Input.mousePosition; will work as expected, because Input.mousePosition returns the coordinates in Screen space
try
Camera.main.ScreenToWorldPoint(Input.mousePosition)
As for the other general issue: https://unity.huh.how/ugui/input-issues
how would i change the transform.LookAt rotation so its actually pointing at the player rather than pointing upwards in the direction of the player (the muzzle flash is pointing at an angle that the player cant see)
Hello everyone. I will try to explain the problem that I've encountered:
I am trying to create a turn-based game. Turnbase structure is approximately: Battle start / (Before Turn / Turn / After turn) / Battle end
Before turn - turn - after turn goes till one side is alive. So the side that has alive units wins at some points and triggers battle end. Pretty standard.
But the problem I have is at this point: I want to trigger some status effects that are placed on character (basically some buffs shall trigger something, like maybe healing at the end of turn).
I have no problem checking if the buff is still there and remove it from character if it expired, but I have problem with actually triggering the active part of the buff.
Do I use Events in this case and subscribe the buff script to "after turn" or "before turn"?
So basically if there's turn end and buff is triggered aat turn end, it will then receive that event trigger and will then fire it's active method?
I am sorry if I am not clear enough, it's quite complicated for me to explain at this point where the problem is.
Hey guys, I'm wondering if deleting unused instances of an object will optimize my game
Since I'm constantly creating instances of prefabs and game objects in my game and there are lots of unused ones left over
I'm sure it would but I don't know the best way to implement such a feature
Are you using a particle system for your muzzle flash or some sort of game object?
Show us the code for your muzzle flash as well how you handle it
i have this code for a tentacle basically. the targetDir is a child of the linerenderer object so that i can determine the angle of the tentacle. How can i add something like a sine wave to basically make sure that the tentacle never comes to rest as a straight line, but in a wiggle.
solved
So, im trying to make an really basic crouch system and there are no errors in the console but i dont really see anything happening when i hold down left control and i dont really know whats going wrong. I made it by myself so I knew there would be some complications.
did you set the values in the crouchHeight?
also where did you put that code in. You should try to put some Debug.Log messages to make sure your codes are being called at least
yeah
ah
ill try
also check the value in the editor, the numbers in the code doesnt matter anymore once your script is read by the editor already
What are you expecting it to do? If controller is just a CharacterController it'll just make the collider shorter
Guys, I have an issue with my muzzle flash. While the effect is working fine, the way it works is that it creates an instance of an object that contains the particle systems for the muzzle flash, however it keeps the unused instaces. Should i use an object pool?
Its definitely being called
@wicked blaze
Here
yeah im reading it all dont worry
Only the collider is getting shorter, not the player itself
yeahhhh i also just figured it out now
how do i make the player also shorter when its pressed
you can change the scale, but depends on your cahracter
if it's like a simple box, that should work just fine
if it's like a human model, prolly not
its an capsule...
i can see that the character controller is changing to 0.7 when i press left control
yea that should be fine, just change the transform.localscale
alright
do i replace the controller.height with transform.localscale or
Just change the transform of your player ```cs
transform.localScale = new Vector3(1f, 0.5f, 1f);
doesn't Vector3.one * height work here
I think so
actually no, that would change all dimensions
yayyyy, its working!
thanks
No problem
im thinking about adding crawling on the floor to my game just dont know how i would turn the player capsule so its in an laying position
oh right it's crouching
Make another variable to go lower and slower
and apply the same logic
transform.rotation = Quaternion.Euler(0f, 90f, 0f); will make it sleep on the ground i guess
izza capsule, it should just roll 
litteraly
i just read that in an italian accent
If you want to stretch the collider across the x axis, add a variable for the length of the collider when laying as well
To pretend you're leaning I guess
yeahh
It's a first person game right?
i just cant imagine when ill have to make an actual player models and then add all the animations for crouching, hitting, crawling, ect.
yeah
If it's an FPS, you don't
Unless it's multiplayer
yeah
Since you don't even see your own player model anyway
So why would you want to add animations and player models?
im thinking about the ones that you can see in first person, if you are doing something with your hand ect
whats the key that is ussualy use when crawling
You can still do that without having to see your own player model
i think im going to have to use C since left control is for crouching for me
z is usually for prone
z is nice as well
Shift for sprint
etc.
You can add a dropdown to change it in the inspector to whatever you think is best
ill see
ill probably add that
It's easy
i kinda forgot whats the normal state of the rotation
Just ```cs
public KeyCode crouchKey;
is it just 0f, 0f, 0f
0, 90, 0 will rotate it 90 degrees in the y axis
Quaternion.identity
It changes based on where you look
alright
Quaternion.Euler results are consistent anyways, (0,0,0) should work, but .identity is the peep for this
definetly works but now i kinda cant even turn my camera or look in other direction
and my crouch kinda stopped working
i can look up and down
but side to side isnt working
Quaternion.identity sets all your rotation to default (no rotation)
Show your code
here it is
i dont really know why the crouching stopped working all of a sudden
you should do a state machine
that make sure you are only in one state of chrouch, walk or crawl
and i have never realy heard of that
something new
Do you have a boolean to check if you're crouching?
just something like ```cs
public enum Movestate { walk, crawl, crouch};
public Movestate currentState = Movestate.walk;
@queen adder
no really
i guess i should probably make one
I think you can just use booleans to sswitch between states, no?
actually, it's quite confusing to implement right now, and i dont really have much time to guide rn
just do a bool that keeps flipping back and forth, easy fix for now 
That's what I do lmao
wait, i dont really know how to fix it
so the looking still works when i crouch
Hi all, I'm having an issue with my EventSystem. I have an EventSystem prefab that has a script attached to it that contains this code to make it persist between scenes and have it be a singleton:
{
if (current == null)
current = this;
else
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}```
I have a scene called BattleScene that contains a Canvas with a button that when clicked, calls a function from the EventSystem (image attached). The EventSystem object referenced there is the one I dragged into the scene.
My issue is that when the "BattleScene" is the first scene loaded, it works fine. But if I start in another scene and then transition to the BattleScene, it doesn't work at all. It's as if the button doesn't have a connection to the EventSystem. What may cause this?
All of my scenes have the EventSystem prefab added as an object
not a good idea to call DontDestroyOnLoad right after Destroy
doesnt matter though?
the problem is the reference is getting lost because they're recycling something from another scene
Oh I see... If you don't mind me asking, what's the best solution in this case?
not do ddol
I moved it to inside the if block. Is that better?
Oh I see
what is TriggerBattleDeckButton
yes
It's a method inside of the EventSystem's script that invokes the "BattleDeckButtonClicked" action
EventSystem is a unity class though, if that is your script, you'll want to rename it, cause it can cause confusion (or potentially errors, someday)
Oh I see, I had no idea. I usually reference it by saying EventSystem.current which gives it the static instance of the class. But I'll change the name just in case.
I tried removing the ddol but that doesn't seem to have worked.
just change your whole awake to current = this
hmm, when using the Quaternion.identity my camera is pointing to one side and i cant really look left to right only up and down.
i dont really know how i can set the rotation to the one that was before
the normal one
This unfortunately didn't work either, but I think I know what the issue might be. When I created my first Canvas, it automatically created an "EventSystem" object. I added a script to this object and made it a prefab. Is it possible that I should have instead just made a brand new "Event Manager" object instead of using the auto generated one?
use a bool that tracks whether ur player is crawling, then flip it when you Input.GetKeyDown(c)
only then you will rotate the player
aha
wait, so am i supposed to put the bool into an if or
i dont really understand
can you send the whole file with the Trigger Battle something? not sure how you made your own method in eventsystem
Oh it was my own script that I attached. But I think that I have a very poor understanding of the EventSystem.
Is Unity's EventSystem set in place so that you can have buttons interact with your game without writing code?
if(isCrouching)
{}
else
{}
}```
the crouching works now, thanks
but still the same problem when i try to craw it just turn my camera to one direction
and i cant move it left or right
only up and down
isCrawling = !isCrawling;
if(isCrawling)
{
}
else
{
}
}```
is this the right channel to ask doubts related to netcode?
Is it a good idea to have a Init method which replaces constructor in MonoBehaviours?
Why do u even have constructors for MonoBehaviours?
Unity builds components themselves. You won't get the chance to call init or the constructor to use them.
I mean, I want to inject a dependency to a MonoBehaviour and I can't find any better way to do it
it's common, but usually Awake work for the job
If you need arguments. I'd suggest make a static method.
Something like this is something like this.
public class MyComponent
{
public int Something { get; private set; }
public static MyComponent AddComponentToThat(GameObject game_object, int value_of_something)
{
MyComponent @new = game_object.AddComponent<MyComponent>();
@new.Something = value_of_something;
}
}
And try not to call AddComponent outside it. :p
I don't normally do this. I construct an entire game object with necessary components instead.
Instantiate(yourClass).Init(34);
it return a generic T
Ah.
Well, I think I'll refactor the code so I don't have to inject dependencies into a MonoBehaviour. Thank you both!

