#π»βcode-beginner
1 messages Β· Page 330 of 1
Yeah, not any special name I've ever heard of
It's usually not needed and has a better way of doing something
alright
then you should maybe watch a C# Course on how to do it correctly
if you wanted an if stament to return true once when an int is equal to 1 how would you do it
code..
if (someInt == 1) return true
return false
why the grin Car
look at the msg above
am i misunderstanding something
of course
thats new for me, thanks
if method returns a bool yea
didnt know you can return a == tho
== is just an operator that returns a bool
just like + returns an int
== doesn't do anything except return a bool
hmm never tried that, so obvious tho
if (someInt == 1) is "returning" a bool
i cant understand this
a == b results in true or false
true or false goes in a bool variable
bool x = true;
bool x = a == b;
same thing
guess i could saved myself a line or two if i ever tried that
luckelly C# doesn't have === like javascript
ugly
luckily C# isnt shit like js
no need to get personal π
indeed return thisint == 1 is ugly
i will continue the if (thisint == 1) return true route
can you show it in a full if statement
show what
um no i was talking about === in js
what you wrote was ugly lol

js as a whole is ugly
but atleast js is not python, python should be a warcrime
uh forgeddaboutit
any bool expression can go in if
I like js cause how you can edit html with it so easely. It's ugly when it doesn't works or doesn't do the thing you want it to do.
well in the web we have no choice when dealing with DOM directly. Anyway we going offtopic here
if all the method is doing, is returning a bool.. I'd do
private bool CheckInt (int someInt) => someInt == 1;
Instead of
private bool CheckInt (int someInt)
{
return someInt == 1;
}```
I do this usually when my method only does 1 thing ^^
Doesn't even need to be returning something
oof the => thing, i understand the usage but dont really like it, i rather do the full one
right now i am doing this and then turning it true again abit later with an Ienumerator
=> has very good uses in c#
guys i get error it says FindObjectOfType<GameManager> is obsolote what should i do
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCollision : MonoBehaviour
{
public PlayerMovement movement;
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Die"))
{
movement.enabled = false;
FindObjectsByType<GameManager>();
}
}
}
switch it to the new method?
but it doesnt work
also you should only need to cache it once in awake
I know i just like the code to be "full" as its more readable for me
sure whatever makes it legible for you but I'm sure with time and more experience you will realize the many useful cases
wait i guess i fixed it finaly lemme try it
you need this one https://docs.unity3d.com/ScriptReference/Object.FindFirstObjectByType.html
also just do it once in awake , no need to do it every collision
- swap to the new method
- you find it, but don't do anything with it
- use !code π to share code so it's readable
π 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.
yup
FindObjectsByType<GameManager>() returns the result of the component find
you're just discarding it / doing nothing with it
It's also only obsolete in Unity 6 preview.. it'll still work
how should i learn coding do u know?
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
do the structured courses on Unity
and the microsoft website good too
is unitys structured courses good?
it would have been cool if microsoft made it and then diddnt explain it
yup
i know the usecases and have stuff like that in my code, just normally i dont use it
what the hell does that even mean lol
chungus
yes
microsoft made c sharp
im watching Brackeys rn. Should i watch first Brackeys video (GAME OVER - How to make a Video Game in Unity (E08)) or unity structured courses?
brackys not good to learn good code
Dont watch brackeys at all
why?
search for C# course to learn C# and Unity 3D course
use the provided resources
bad tutorials, bad code, missing info, etc
Well, for one, it'd be a pretty bad idea to start with episode 8
- teaches bad practices
- has an error in one video that plagues this channel
- is old and becomming outdated
i started it at episode 1
haha need a macro for that
Brackeys is great for learning specific tools Unity has. Not so much for general C# programming. You should probably know code before going through Brackeys content
ok ty guys
also it doesnt teach unity doesnt it?
this is to learn c# which unity API uses
its not unity-specific no
why should it
what does mean unity API
its just c#
basically to interact with another APP
through code
application?
ahh
since the original engine is C++
Application Programming Interface
Unity has its own suite of functions and classes, but C# contains many things that are not Unity specific
Unity's API is a small subset of C#
and we can use it on unity or?
You can use c# anywhere you want
You will be making C# code that uses some Unity functions.
But it's not a special flavor of C#, it's just C#
But API is not what
API is an Endpoint on the web
GET / PUT
no its not
REST ETC
REST and API are not the same
API is not a web related thing
Api stands for Application Programming Interface, as I just said
REST is an example of an API
API is just basically software to software communication
Rest API is the interaction between frond-back end. Different than api
It is the way you interface with a program/app/library/etc
Did infact not knew that, i thought its web only, especially REST, etc
API = Rectangle
REST = Square
All squares are rectangles. Not all rectangles are squares
a telephone for software!
idk what api is. Even tho it means Application Programming Interface i still dont get it
Good analogy
it doesnt matter
learn C#, thats the language Unity uses
A thing that lets you code for a program that already exists
then learn Unity and how to code in Unity
As opposed to making an entire new program from whole cloth
void Update()
^ this is part of the Unity API
Unity provides an API that you can access through C#.
hm i guess i understad a lil
All the methods and properties exposed by Unity are the api
Basicly an extension on an existing language?
It allows you to interact with Unity things like Rigidbodies, Materials, Transforms, etc.
after learning Unity courses then what should i do?
Make games.
practice
Dive into the real deal
Is unity courses teachs everything?
Pretty much.
You were recommended a c# course too
then how can i learn new things with making games
No one person will ever know everything. What's important is that you learn how to learn what you don't currently know
How can you not?
start small
Making mistakes and exploring IS learning
i cant write what i dont know , so i cant learn new things
its more important that you know WHY and HOW its moving something for example, rather than pasting code you dont know / understand
The unity courses teach you more than enough to write things you don't know
It's all small pieces that you put together into big programs
The course teaches you the small pieces
Then you just look at the docs when needed
Unity docs has lots of examples
If you want. Basically no. Read them a lot, but don't just sit and read the whole things without a goal in mind
We have said a few times, do the unity course, then make games
hm ok i got it when i need it
ty
That is the whole point of API's. once you know them the 'new things' come from combining them in new and interesting ways
can u give me a lil example pls?
Subnautica
It was made with unity
no i mean about this sentence
sure.
take the Unity Vector3 struct.
one you know it it can be used as
- A position
- A direction
- A Velocity
And many more things
hm okay ty
so first i'll watch unity courses then making practice and i'll use doc. when i need it right?
absolutely, you should always consult the docs when taking the courses so you really understand what they are trying to teach you
i have 1 more question
should i watch other tutorials even tho i finish unity courses
or make game and sometimes i should watch courses
you can watch other tutorials because some of them provide additional information and techniques not covered by Unity. And by that time you should be able to tell which ones are worth watching and which ones are not
should i watch these tutorials when i need it or daily?
When you need it
Try to do it more rarely. Give it a shot on your own first, then if struggling look at a tutorial
hm okay ty again xd cya
hello , i have something i want to do but i am not able to , here is my map for example
i can move the camera around
and zoom in and out
( it doesnt follow any particular thing i just move it around )
but i want to bound the camera to the edges of this map
i thought about creating a gameobject with a 2d collider which represents the bounds of the map and try to check collisions with the camera but i dont really know if its the best way to do it
any ideas on how to do this ?
i can bound the movement easily
but the zoom ...
obligatory: use cinemachine
it also has a confiner component
hello how dfo i move this im using the game scene any1 got vid? i looked and didnt find
that 4x4 i crated using this
check the documentation pinned in #π²βui-ux to learn how to use UI
I don't know why this hide cursor script isn't working, when I add it to either the player game object or a cinemachine camera it doesn't work.
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HideCursor : MonoBehaviour
{
void Start()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
}`
make sure to click into the game view window. the editor will not capture the mouse otherwise. the editor will also release the mouse regardless of the Cursor.lockState when you press escape so don't expect that behavior in a build without coding it yourself
Thanks, is that on by default if I click the game view?
what are you referring to?
In past unity versions I always needed to add the two lines of code, but you are telling me otherwise.
i never said you didn't need to do that too. i just said that it won't work unless you also click into the game view. which is how it has always worked
apparently if I make the script un active the cursor hides by default if I click the game view, hide cursor is on by default now(if you click the game window).
you are probably disabling the component after that code has already run
how 2 make dragging for 3d object? i just need 2 get mouse coords & some method for getting x & z from it, y is a constant
ScreenToWorld method in camera orScreenToRay then use a plane
about first, object is on the front of camera but i don't see it. about second, it doesn't existis in this context
can you show what you have so far, I'm a little confused on how you set it up .
object, camera
& i'm trying to set up y as 0.35
transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Figure.size / 2));
size = 0.7
hi! is there an easy way to flip my 2D sprite without moving my character?
right now, when the sprite is fliped, this happen
gameObject.transform.Rotate()?
Should I just change flip for rotate in the code?
you need to adjust the pivot point of your sprite in the sprite editor so that it is centered on it
Change the origin point of your sprite to the center. Either through the pivot point of the sprite itself, or by making the renderer a child object of the collider and changing the center point that way
isnt already centered?
It's the center of the file, but is your sprite actually in the center of the canvas?
If not, you'll need to put the pivot on the center of the sprite you actually see
oh ok
is there a way of changing the pivot of all sprites at the same time?
I undestand what you mean, the pivot is centered here instead of the body of the warrior, but when I change it it only apllies to that specific sprite, which causes errors in the animation
the best thing to do is instead to design your sprites so that they are properly centered. or slice them so that they are centered
Doesn't seem like it. Your best bet might to be to change the sprites themselves so they're all centered at the same focal point. This means you might need to adjust the width of the canvas so they're all able to fit about the center of the canvas
it's not going to quite turn out the way you want for some of those sprites though
You might need to do some manual adjusting of those sword swing sprites but it is at least most of the way done for you
yea is oj
ok
I think the majority will do, I'll adjust manually the problematic ones
(sorry to transform the discuss from code to pixel art xD)
i have some problems with my blind enemy AI. here i have this script which adjusts the volume and range of currently emitted audio (this script is attached to the player):
using UnityEngine;
public class SoundsEmitter : MonoBehaviour
{
//emittedAudio[0] - loudness
//emittedAudio[1] - range
public float[] emittedAudio = new float[2];
public PlayerMovement playerMovement;
private void Update()
{
AudioChange();
}
private void AudioChange()
{
switch (playerMovement.state)
{
case PlayerMovement.PlayerStates.Standing:
emittedAudio[0] = (float)PlayerMovement.PlayerStates.Standing;
emittedAudio[1] = (float)SoundsManager.SoundDistances.Standing;
break;
case PlayerMovement.PlayerStates.Walking:
emittedAudio[0] = (float)PlayerMovement.PlayerStates.Walking;
emittedAudio[1] = (float)SoundsManager.SoundDistances.Walking;
break;
case PlayerMovement.PlayerStates.Running:
emittedAudio[0] = (float)PlayerMovement.PlayerStates.Running;
emittedAudio[1] = (float)SoundsManager.SoundDistances.Running;
break;
}
}
}```
the emittedAudio[] is an array, because the first index holds the volume, and the second index holds the range the currently emitted sound can be heard from.
i also have this Blind Monster AI script. it's long so here's the link to PasteBin: https://pastebin.com/k2dVG1yN
the problem is that the monster doesn't care about the player at all, though it correctly gets the `emmitedAudio` variable from `SoundEmitter` component in `source` (look at foreach loop in `CheckAudioSources()`). i adjusted the maxLoudnessLimit and the enums values correctly. I don't know what's the issue, could someone help? I'll be thankful
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
the problem appeared after i changed emmitedAudio variable from a single float value variable to float[] array. the previous single value variable was holding just the volume.
the problem is that the monster doesn't care about the player at all
what do you mean by that? as in it isn't using the correct value from playerMovement.state? because if that is the case, you may be referencing the prefab rather than the active player in the scene
by the "monster doesn't care about player at all" i mean that no matter how close i get to the monster and how much noise i make, it doesn't make the monster chase me. i checked that while running the volume is set to 100 (4 is enough to make the monster trigger a chase), and the distance between me and the monster is enough to make it chase me, but it doesn't happen.
you have a whole bunch of conditions that affect whether that object will enter the chasing state and whether it will actually set the destination. either use breakpoints to inspect the values you are checking, or print some useful information that actually tells you what is happening when you check those conditions
i will, thanks.
and keep in mind that you can use string interpolation to construct a single log that provides useful information. so instead of just dumping the individual values stored in your array right to the console like you're doing on lines 64 and 65. for example:
Debug.Log($"Emitter at loudness threshold: {emitter.emittedAudio[0] >= maxLoudnessLimit} and monster state {state}");
i know, i'm using it all the time. thanks for reminder though
hi just asking how would i be able to, after picking something up, rotate it to a certain specified orientation then just not rotate it anymore?
transform.Rotate
lerp
i know i can rotate things with transform.rotate but how can i use it to only make it rotate to a specific point then stop
oh, thanks didnt know that existed π
Hi. Trying to use RayCast, but it detects only one side of a cube. What am I doing wrong?
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private float moveSpeed = 7f;
[SerializeField] private float rotationSpeed = 10f;
[SerializeField] private GameInput gameInput;
private bool isWalking;
private void Update()
{
Vector2 inputVector = gameInput.GetMovementVectorNormalized();
Vector3 moveDir = new Vector3(inputVector.x, 0f, inputVector.y);
float playerSize = .7f;
bool canMove = !Physics.Raycast(transform.position, moveDir, playerSize);
Debug.DrawRay(transform.position, moveDir, Color.red, 1f, true) ;
if (canMove)
{
transform.position += moveDir * moveSpeed * Time.deltaTime;
}
isWalking = moveDir != Vector3.zero;
transform.forward = Vector3.Slerp(transform.forward, moveDir, rotationSpeed * Time.deltaTime);
}
public bool isPlayerWalking()
{
return isWalking;
}
}```
I can't see the debug ray in the second case, where is that line appearing on that side?
I will make this line a little bit cleaner.
when i want to debug.log() the emittedAudio[0] and emittedAudio[1] values, instead of showing the enum value (i store enum values in these 2 indexes), it shows the index of enum. for an example, Standing's value is 0, walking is 10, and running is also 10, but instead of showing these variables it shows 0, 1 and 2. it's only for SoundVolumes, SoundDistances work fine:
this script is binded to the player:
using UnityEngine;
public class SoundsEmitter : MonoBehaviour
{
//emittedAudio[0] - loudness
//emittedAudio[1] - range
public int[] emittedAudio = new int[2];
public PlayerMovement playerMovement;
private void Update()
{
Debug.Log(emittedAudio[0]);
Debug.Log(emittedAudio[1]);
AudioChange();
}
private void AudioChange()
{
switch (playerMovement.state)
{
case PlayerMovement.PlayerStates.Standing:
emittedAudio[0] = (int)PlayerMovement.PlayerStates.Standing;
emittedAudio[1] = (int)SoundsManager.SoundDistances.Standing;
break;
case PlayerMovement.PlayerStates.Walking:
emittedAudio[0] = (int)PlayerMovement.PlayerStates.Walking;
emittedAudio[1] = (int)SoundsManager.SoundDistances.Walking;
break;
case PlayerMovement.PlayerStates.Running:
emittedAudio[0] = (int)PlayerMovement.PlayerStates.Running;
emittedAudio[1] = (int)SoundsManager.SoundDistances.Running;
break;
}
}
}```
while this one is binded to a standalone empty object SoundsManager:
```cs
using UnityEngine;
public class SoundsManager : MonoBehaviour
{
public enum SoundVolumes
{
Standing = 0,
Walking = 10,
Running = 10
}
public enum SoundDistances
{
Standing = 0,
Walking = 10,
Running = 100
}
}```
I think the lines at the right situation is not detecting collision right.
you aren't printing the enum values here, you're printing the integers stored in your int array
how do i get the enum value?
That's quite a bit of lines. Since you're drawing it every frame, having it last 1 second is going to make it hard to spot. You should leave off the last two parameters of that DrawRay
you are casting them to int, just cast them back to the enum if you want the enum or store them as the enum instead
Then you should be able to see where the line is at that exact frame
ok, thanks
but if they are printing values you do not expect then you are either using the wrong enum types, or you need to actually save your code so that the enum values are properly compiled
I have propably spotted the issue. Let me check and I will be back.
Ok didn't work. When I leaved off only two parameters the line is really hard to spot.
It is in Update so it'll get drawn every frame. If it helps, you can multiply moveDir by some value in the debug drawRay to make it longer
Great idea. Will do that now.
Ok, the issue was RayCast was too low on Y axis and was interferring with floor. I modified transform to add +1 to Y axis and now it detects obstacles correctly. Thank you for help.
how come doing "whilst bool is true" crashes the game
infinite loop
while(true)
oops
the loop would end when the bool is false i think
while (true);
more whoops
if its inside coroutine it needs yield return null inside
how come
cause it wont know when to end
okay swag
Does anything inside the loop ever set the bool to false?
it does but not with an ienumerator
Hey hey good people. I'm new to Unity and I'm making a topdown 2d shooter.
I have an issue with my firing where instead of going forward from the front of the character it goes into a random direction (maybe my implementation is wrong.)
So, i have a square with a rigidbody2d attached with an empty sprite that's used as the projectiles starting position. The projectile should go from the empty sprite towards the mouse location but it's instead flying into a semi-random direction
I'm using the following implementation:
Projectile behaviour script:
https://hastebin.com/share/obuciluzah.csharp
Player Rotation Script:
https://hastebin.com/share/afiwinuges.csharp
Player Projectile Launcher:
https://hastebin.com/share/ijicuhurav.csharp
would be grateful for a solution π and please do message me if you are missing any info (I'm new to this).
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
If there's no yield statement inside the loop, the entire game engine is waiting patiently for the loop to end before continuing to run. So nothing outside the loop can affect anything and if the condition doesn't become false4 in the loop, it will be frozen forever.
Your playerMousePosition is always 0,0,0
you never set it to anything else
The variable in the PlayerAim script is completely unrelated to the one in this script
Also why does it seem like the gun is launching itself based on this code?
Yes, thank you. The PlayerAim script is just for rotating the character actually. I'm ashamed I missed it, thanks for the help π
There isn't actually a gun. Just based on the weapontype it will load a different sprite (will add later on) and the projectile behaviour will be different.
okay i get them now
why does my player move like this?
void FixedUpdate()
{
Move();
}
void Move()
{
moveDirection = GameManager.input.Player.Move.ReadValue<Vector2>();
print(moveDirection);
rb.AddForce(moveDirection * moveSpeed, ForceMode2D.Impulse);
}
You mean the jittering?
It's because you don't have interpolation enabled
not the jittering, thats from my recording software or pc idk but in the game its not there
its very fast
so how do i apply less?
You also have the ForceMode set to impulse which applies a short burst of force (which may or may not be intentional)
would it be alright if i divide the move speed by 10 when applying the force? so i can keep it a value like 5 or 10
you can do whatever you want
it just will be in a weird unit
"tenths of a newton"
i dont really know the differences between the force modes but ForceMode2D.Force doesn't move my player
You just need a higher number
basically the only difference between Force and Impulse is that you will need a number 50x higher with Force to do the same as Impulse
(assuming you didn't change your fixed timestep)
All of these are equal:
AddForce(moveSpeed * move * 50);
AddForce(moveSpeed * move / Time.fixedDeltaTime);
AddForce(moveSpeed * move, ForceMode2D.Impulse);``` @paper sable
oh alright thanks
Why this code not work
public GameObject door;
public void DoorOne(string answerText, GameObject doorObject)
{
this.answer = answerText;
this.door = doorObject;
}
And this code work
public string answer;
public GameObject door;
public void DoorOne(GameObject doorObject)
{
this.door = doorObject;
}
what makes you think it doesn't work?
Also is this on a MonoBehaviour?
Why i use the code "not work" i can't see on here.
how do i scale an image between two points on screen?
I don't see DoorOne anywhere here
Seems like you're looking at the wrong script entirely
unity events do not support more than one parameter
yeah, it the problem
In what context? Is it UI?
yes
oke thank you sir
image size: 64x64
So, how do I trick it into working?
you use a method with only a single parameter
but i need 2
well too bad, unity events only support a single parameter.
you can call a multiparameter method from another method that only has one parameter though
LineRenderer would be easier
that doesnt work
jsut set those parameters in the inspector on your button and call a function that calls the other function with the params
sure it does
can't the doorObject contain the answerText?
line renderrer
You just have to understand what you're doing with the positions etc.
Makes sense, thank you
i know what im doing, it shows in editor, but not within game
Then you are doing something wrong π€·ββοΈ
Show what you did when you tried the line renderer
That's not the problem. Apparently unity doesn't support doing my code which doesn't work.
They are suggesting a workaround for that issue
THen you did it wrong
i didnt
If it didn't work, then you inarguably did it wrong
My guess is you are confused about canvas space vs world space
A LineRenderer would draw things in world space - so you'll have to do the appropriate conversions for it to show up in the expected position in the game world
i didnt
and yes, i know the line renderrer will draw in world space
These are super unhelpful responses.
Why not just show what you did?
what do you mean
You had trouble getting LineRenderer to work. Show what you did that wasn't working, we can help fix it
What do you mean what do I mean?
Show what you tried with the line renderer.
You did something wrong, we need to see it to tell you what it was
lineRenderer.SetPosition(1, screenPos);```
Ok and what are LeadPos and screenPos
how were they calculated?
What coordinate system do they exist in?
vector 3
π€¦ββοΈ
both
??? wdym both
It's one or the other
Your answers to my questions are only confirming my suspicion from earlier that you don't understand the world space / canvas space distinction
both are in vector 3
screen pos is the square pos
the leadPos is the complex mathematical equasion that does the leaning where i need to shoot
vector3 is not a coordinate system
it's a datatype
and obviously it's a Vector3, that's what SetPosition accepts as a parameter
that's not what I was asking
The answer to how to fix that is you need to make sure both positions are in world space before using them with LineRenderer
(and that LineRenderer is set to world space mode)
lineRenderer.SetPosition(1, target.position);```
and nothing, like before
there is no line
sometimes i know what to do after typing the question lol
Are predictedPosition and target.position both in world space?
yes
Use Debug.DrawLine as well just to show where this line is actually
That's a pretty common thing. It even has an adorable name and origin story.
https://en.wikipedia.org/wiki/Rubber_duck_debugging
that is neat
Gonna be hard for us to tell where that's supposed to be in screen space since it's just a still image of a line but is that debug line covering roughly where you expect it to be
the line is showing corectly
but idk why line renderrer it isnt in game screen still
so i switched to image method and now im missing the lenght calculation
Where is the camera in this situation? Can you send another screenshot with the camera selected so it draws the camera's frustum
And if possible try to rotate the camera so we can get a good view of where the red line is in relation to it
It's hard to convey line renderers in still images since there's no depth. Assuming the game's still running but paused, can you get a shot of this from the side as well?
Perfect, video is definitely best for this but it can be annoying to record and share, thanks for that
yes
So it should definitely be visible at that position. A bit small, but not so small it's not visible. Can you send a screenshot of the line renderer component while it's still paused like this? You should be able to see the positions in the inspector for it. Do they match what you expect?
ey
i fixed it, it didnt have an material
Ah, that'll do it
tnx for help
what does transform do
It is a component that contains position, scale, rotation, parent, children, etc
Every GameObject has a transform (or rectTransform)
ohhh
thanks i forgot about those
i was confused where it was coming from
lmao
Hi, i have animations for my player, its a topdown 2d game. My player has 4 animation for running, and idleing. Top down left right. My question is now my player always face down when i stop moving. How can i like save the last moved direction and play that animation. For example if i run up and i stop, the idle up should play, not idle down.
how come an animation that isnt being activated is making my enemy not be able to move
how do you know its that animation that isnt even being an animation is making your enemy not move?
because when i remove the animation from the animator controller it moves again
Does the animation affect the object's transform
yeah it moves down
You should be animating a child object, not the actual object you move around
how does that work
- Object you move with controls
- Object you move with animation
i see swag ty
transform.GetChild(0) is causing 'Transform child out of bounds" when called frequently. Is this normal?
It's completely normal if the object you call it on has no children
All the objects being called have children, once the function is called ~30 times it stops working and the error is thrown.
Before the line, add this:
Debug.Log($"{gameObject.name} has {transform.childCount} children");
And look at the most recent one before that error occurs
thanks Ill try that, but I can see that the game object has children in the editor
!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.
Maybe it's removed then put back?
private void TriggerSelectionIndicator(GameObject unit, bool isVisible)
{
unit.transform.GetChild(0).gameObject.SetActive(isVisible);
}```
The function is pretty simple, maybe its the SetActive part
Okay, if that's the one, the log should look like this:
Debug.Log($"{unit.name} has {unit.transform.childCount} children");
what is the point of the non generic getcomponent?
Compatibility, from before Generics were supported
interesting
yeah
I see
wouldnt that be called concatenation or am i mistaken
No
Concatenation is combining collections
String concatenation would be using +
i see
thanks for this debugging help, I've identified the problem with itπ
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float Speed;
public float JumpForce;
private Rigidbody2D rig;
// Start is called before the first frame update
void Start()
{
rig = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Move();
Jump();
}
void Move()
{
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * Speed;
}
void Jump()
{
if(Input.GetButtonDown("Jump"))
{
rig.AddForce(Vector2.up * JumpForce);
}
}
}
i still cant jump
can soembody help me?
ur overriding position
every frame
how can i fix it?
if its a rigidbody it should not even be using transform. You should use velocity , or AddForce
if you use velocity you make new vector2 keeping y as rb.velocity.y
leave the Y velocity alone (like he mentions ^ just feed it back to itself)
how can i do that?
replace this line
transform.position += movement * Time.deltaTime * Speed;
with the proper one
rb.velocity = new Vector3(Input.GetAxis("Horizontal"), rb.velocity.y, 0);
but w/ ur smoothing and stuff
ok
keynote.. u pss its own velocity.y back to teh Y
Is it best practice to use the Animation system as a State Machine?
As in using the Animation system to create a State Machine that does a lot more than animation.
its not a best practice but a choice . . .
if u have to knowledge to be able to use the animator as a state machine..
you probably have the knowledge to build out a custom state machine to use
why does it say i dont have data to save when i do? and i checked and my save file didnt create for some reason
hey guys i have a problem but its not with code can i ask here?
this is a coding question channel so no
then where?
browse the channels for the correct category . . .
we have no idea what kind of question you have. only you do . . .
Any idea on how to do a dash but when the player quickly presses the move button?
check the input of the player and AddForce to the rigidbody
the thing is I dont know how to do the code for it to happen only when you press fast the moving input
how else do you press it, slow?
there is no speed in pressing a button
its either pressed or its not
Im talking about pressing the button twice in order to do dash
but those presses need to be fast
ok well thats something
you can use a timer and check if its hit twice within a certain time
if(Input.GetKeyDown(KeyCode.RightArrow))
{
timer = Time.deltaTime;
if (Input.GetKeyDown(KeyCode.RightArrow) && timer < _dashRepeat)
{
timer = 0; Dash();
}
else
{
timer = 0;
}
}
is it okay like this?
start a timer when the first press occurs. if a second press happens, check if the timer is under the threshold for a dash . . .
idk what im even looking at with this code.
first of Input.GetKeyDown runs once
does anyone know on why this happens 
what?
Using code from 2 different tutorials i followed from youtube, one controlled the camera and player movment and now im trying to use code from another person which allows me to interact with objects. im having a problem that rather than the crosshair being where the raycast is sent from, instead it comes from the mouse. im not sure how to change it but ive found the line of code which the raycast is emitted:
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
How do i change it from being the mouse position to instead be the crosshair or raycast from my camera?
get the position of the crosshair and use that instead of the mouse position . . .
how?
maybe, by accessing your crosshair GameObject and getting the position? we don't know how your crosshair is setup at all . . .
tbh im very out of my depth here, i already have raycasting for another interaction script i just dont know how to port it over to this
im extremley new to this and have just been following tutorials
then i would take a step back and learn something simpler . . .
Vector3 cameraPosition = Camera.main.transform.position;
Vector3 cameraForward = Camera.main.transform.forward;
float rayDistance = 10f;
RaycastHit hit;
if (Physics.Raycast(cameraPosition, cameraForward, out hit, rayDistance))
{
// this would raycast from your camera *straight forward*
}```
it's hard to help if you don't understand the help given . . .
the question is a bit puzzling as well
basically what i want to happen is when i look at an object with the script attached to it the item name will appear on screen. the code works but what i think is happening is because if followed a differnt tutorial for how the players camera functions its not working correcty. the raycast isnt coming from the centre of the players fov or crosshair but instead its coming from my cursor on screen. its a first person game and the cursor shoudlnt be there
can i send videos or stuff in here
the codeblock i sent raycasts from the camera
str8 forward (camera's forward) it should be where ur crosshair's pointing (if ur croshair is indeed in the middle of the screen)
so where do i place that in the code
where ever you need the raycast to happen
Vector3 cameraPosition = Camera.main.transform.position;
Vector3 cameraForward = Camera.main.transform.forward;
float rayDistance = 10f;
RaycastHit hit;
if (Physics.Raycast(cameraPosition, cameraForward, out hit, rayDistance))
{
var selectionTransform = hit.transform;
interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
interaction_Infor_UI.SetActive(true);
}
else
{
interaction_Info_UI.SetActive(false);
}```
nice!.. it would look similar to this (im just using ur code as is)
ya, see.. not too hard..
just gotta step back.. look at it.. figure out kinda how its working.. and trial and error
now im having the issue that the text doesnt dissapear until i send the raycast onto a different object in range
thanks
a lot
u probably want to add another else statement. at the end of ur if(physics.raycast)
soo.. if it doesn't hit something in the distance it'll also set it false
so.. if(it hits something and its not interactable) -> set false
and.. if(it just doesn't hit anything) -> set false also
well i broke soemthing
if (Physics.Raycast(cameraPosition, cameraForward, out hit, rayDistance))
{
var selectionTransform = hit.transform;
if (selectionTransform.GetComponent<InteractableObject>())
{
interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
interaction_Infor_UI.SetActive(true);
}
else
{
interaction_Info_UI.SetActive(false);
}
}
else
{
interaction_Info_UI.SetActive(false);
}```
yea thats what i got
lemme try and figure it out for myself firsd
first
gimme 5
thank yo tho
but u do realize.. ur calling getcomponent twice.. everyframe now...
var selectionTransform = hit.transform;
InteractableObject interactableObject;
if (selectionTransform.TryGetComponent(out interactableObject))
{
interaction_text.text = interactableObject.GetItemName();
interaction_Infor_UI.SetActive(true);
}
else
{
interaction_Info_UI.SetActive(false);
}``` heres a better solution
you figured it out or not?
your missing a } to close off the first if
Extra }
put a } between the red } and the else below it
Oh no, in the wrong place
and remove that oen at the end u added
think of it like this
if { and } else { and }
and my only other experince is phython basics
you'll learn.. practice makes perfect
hopfully soon cuz i have procrastinated this project way to much
Ok we wonβt blame you then cuz python uses none π€£
but yeah thank you so much im sure this has saved me ages
python dgaf π
C# brackets are better, itβs like keeping the code contained and organized
i like how random discord strangers are more help than the people employed to teach me this stuff
exactly..
we're procrastinating too.
only a different kind..
i had about 6 months to do this proejct and now i got like a week and a half
lightwork
sounds about par for what i normally see in here..
people come in here stressing "bro, i gotta build this game in 1 week"
oh really.. how long have u had to work on it?
"3 months"
it almost makes us wanna watch u burn..
good
good to know im not the only one tho
BUT.. if u have valid excuses.. and are really trying.. we still help
its the ones that just want copy/paste code that really push my buttons
tbf when we first got it i started really well and then everything corrupted and i didn tthink to kep a backup so i lost a lot of motivation and did other stuff
I think most people go through the same issues just at a different time in life
i mean understandable
the hardest lesson to learn
backup.. and backup some more
some of my projects have been in the works for over a year
i get the same with other stuff in life where people just want the awnsers and cant be arsed learning
Means you gained experience tho, build something better. Not bigger, just use that knowledge now
if they corrupt i'd throw my PC out in the street
tears would be shed
you can lead a horse to water..
"teach a fish to man and fish a day for fish"
exactly
well if it all breaks again im sure ill be back in here sometime soon
but naaa i got this light work ez clap
thank you tho for ur help
much appricated
π good luck sir, π
you too tho im sure you dont need it
oh we.. all do
duno if that makes me feel better or more worried but ill take it how it is
well, its b/c the more advanced u get.. the more advanced stuff u try to do..
if ur not pushing ur boundaries. u aren't learning anymore
Any ideas on why? 
Most people arent gonna watch a video to see your code. It really is tedious, just paste it according to the rules
Hey I am having a problem uploading to playstore. They keep complaining about policy violation I don't know what I violated. I have read their emails and it is not helping either. After the last build I send, the app got suspended.
back again. this time im just confused why this doesnt work. whats meant to happen is when the player enters the collider it sets the "playerinrange" function to true and when he leaves the collider it returns to false but it just isnt doing it and idk why . hole point is once the player is in range to interact with the object they can pick it up but i cant get this working
Hover over "OntriggerEnter" and see what the warning says
Hover over the three dots
. . .
Dang. Alright
bro capital T π
if youre using vs there should be a snippet when you start typing out ontrigger enter
make sure to go over the C# basics as they are vital . . .
Hi, what is the best way for create rooms in a topdown 2d game? I have a room, when i go to the door, i got teleported to the corridor, like old RPG games or like Stardew Valley. I did this by build the corridor far away from the room, and modified the player position on door trigger. Is it good, or how should i do this?
if it works it works
if it works, it works . . .
nice
true haha
you could also split it by scene if your map is larger but dont over complicate it if you dont have to
your solution sounds fine
new to unity events, im trying to make a pointer enter, then it enables the outline over whats being hovered
it works but never goes away after moving the cursor
i made an exit but now it never shows up
Btw i have a UI image for a bar, it act weird, i set native size, then the box does not match with my sprite like this:
Whats wrong?
place a log in the exit method to check if it gets called . . .
alright i did, it did the enter and exit at the same time
when does exit get called?
Untick the raycast target option on the outline image
It's blocking the cast to the object you are hovering causing it to exit as soon as the object is set active
oh interesting thanks!
its for me or for Frostyio?
me
oh okay π
Clearly not you since none of that was relevant to your issue which also does not appear to be code related
Ye but my sprite have Raycast option thats why i tought haha
also odd thing... it works for 1 of the objects not the other 3 but ill look into it a little more firist
@summer stump
using UnityEngine;
using UnityEngine.UI;
public class InteractionPrompt : MonoBehaviour
{
public Image promptImage; // Referencja do obrazka SpacePrompt
void Start()
{
// Ukryj obrazek SpacePrompt na starcie gry
promptImage.gameObject.SetActive(false);
}
void Update()
{
// SprawdΕΊ, czy gracz jest w zasiΔgu interakcji z jakimΕ NPC
bool playerInRange = IsPlayerInRange();
// WyΕwietl lub ukryj obrazek SpacePrompt w zaleΕΌnoΕci od tego, czy gracz jest w zasiΔgu interakcji
promptImage.gameObject.SetActive(playerInRange);
}
// Metoda sprawdzajΔ
ca, czy gracz jest w zasiΔgu interakcji z jakimΕ NPC
private bool IsPlayerInRange()
{
// SprawdΕΊ, czy w zasiΔgu interakcji z graczem jest jakiΕ obiekt z tagiem "Blocker"
Collider2D[] colliders = Physics2D.OverlapCircleAll(GameObject.FindGameObjectWithTag("Player").transform.position, 1.5f);
foreach (Collider2D collider in colliders)
{
if (collider.CompareTag("Blocker"))
{
return true;
}
}
return false;
}
}
(the comments are in polish, dont worry ab that btw)
Someone? Please? π Can't figure it out
!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.
sorry mate
Should definitely only get the Player reference one time.
Is 1.5 gonna be far enough to get it?
you'd have more luck in the actual UI channel . . .
erm.. wanna come vc?
No
im kinda new in Unity and would use some help
sad, but okey
that's why you're asking here, no?
maybe, idk, still new here
As suggested in #π»βunity-talk you should show the inspector for the player
so you don't know if you're here to ask for help?
Also show the inspector for that script
I am, thats why we are talking rn
wait, slow
gotta find that first
exactly. i'd respond to their questions so they can further help you . . .
i hope thats what you wanted mate
Ok, 1.5 should be big enough then. Your player is quite tiny
Now the inspector for the script you showed
i changed that to 3 and nothing happened so
Ah, it is ui
Oh, nm
That should be fine. Show the object you are checking for with the Overlap
you mean the NPC I want to be in range with for this prompt to apear?
I dunno. The thing you are checking for. The one tagged blocker
0,0,0?
isnt that bot left?
Maybe I'm misremembering things, just create a UI element that's a child of the canvas and copy it's world position
Correct. That is bottom left.
Center is x resolution / 2 and y resolution / 2
Why is the collider size absolutely massive when the scale of other things is tiny
It is also offset 4 meters left
i want it to always center no matter what, ig imma just do resol/2
dont know mate
just... happened
like I said - im new to unity
the offset is gone btw
i remember theres some method specialized at getting screenspace thingies before tho
i hate that resolutions arent given as v2's tho 
Well, everything looks superficially set up right. The collider is there, the tags are right, the code is valid.
I would do some Debug.Logs to verify what code is running. Add values like the players position and cound of colliders picked up. In the foreach log the name of the object
It does?
Debug log should be the absolute first line of code you ever wrote
I recommend !learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
ty for trying mate
Oh, but did you reset the collider size?
Well do that.
Set it to 1, 1
And offset to 0,0 if it isn't already
colider of Blocker you mean?
Yes
and now I can walp through an NPC
well... half of him at least
and the prompt is not showing still
Alright. Well, debug.logs are gonna give you the answer
Can i use a custom shader or camera to take in a cubemap and render to the rendertexture?
maybe
my overall goal is to have a camera that renders to a cubemap, and then a shader that samples that view (with panini projection) and outputs to the screen
hrm okay
odd issue i'm hoping will have an easy fix, there is a scriptable object for each card in my game and their can be duplicates of the same card
but now testing out battles i dealt damage to the opponents card but it changed the health of every scriptable object that was the damaged card
will i be forced to have some type of cardWrapper object to put it in?
Don't modify SOs at runtime. Generally treat them as immutable.
Generate a class from the SO data, and modify that class
So I guess yes to your last message
Its my first time using visual studio with unity and codes in general i'm on the latest version of visual studio does anyone know how to fix this?
What version of visual studio is it?
17.9
Hmmm... is that the sub version? Or is it not 2019 or 2022?
could i manage the card's in battle health inside of the battle script? not changing the SO's fields at all then
any way I can recreate this effect in unity? (merging vertices based on the distance from an object)
Sorry, not sure what you mean. As long as you are not changing the SO fields, it is fine. Read from thr SO, write to a POCO or MonoBehaviour
I would close visual studio completely, go into unity, go to the edit > preferences > external tools menu, and click regenerate project files
in my script that manages using abilities, and battling i could make a variable(s) for currentHealth and when loading cards assign the health to the SO's max health
then change it from there
Without implementing it yourself, the closes is REPLACING the model with LODs
If it works it works. You just need individual instances for each card
might be a little annoying, it'll just be 6 int variables that change every battle instance
Yeah. I would definitely recommend doing a POCO and just storing a few lists or arrays of the ones in your hand, on the "field", in the graveyard, and in the deck
The constructor for the poco would just take the SO and populate its values from that
But there are lots of ways to do it
I dont think it worked
Don't put breakpoints there π€·ββοΈ
Are you opening the project from inside unity?
Hey yall, im trying to implement a system that allows me to save the players progress through files. The problem? The player picks up items that are added to the players class, each of these items contains a sprite. Whenever i convert my classes to json and add them to files I cant load the sprite back into then item. Im trying to use a class for sprites that maps their location to a id reference i save the id instead of the sprite and then use a function from this class βgetsprite()β to find it. But i cant seem to make it work for the life of me! Am i going about this all wrong? Does anyone have experience with this or have a simpler way?
what is POCO? i think i'm going to use a wrapper with a constructor for the base item with properties
Plain old c object.
public class Foo { }
oh lol
Does not inherit from MonoBehaviour or SO or anything
here look at what i found online which i think will work
spiney199 example
4th comment
i think that's what your referring to as well?
Didn't read too much, but what the second comment is saying is exactly what I am suggesting
Yeah, and the 4th
alright cool, might have a decent bit of work to do fixing this around then
least i did this earlier than later
Every new code i write, i literally can't debug.
Why are you trying to breakpoint a curly brace
there's no code there, it can't break on that
Here's some non curly brace examples.
Is your !ide configured?
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
It should be tbh. There are places where debugging does work (though scant). And i do get highlighting and warnings.
Ok i added random code.
It can break on the previously cannot be found ones.
What is happening. 
That is odd. Not sure.
I guess try going through all this
#π»βcode-beginner message
Could be an issue with your cs project or solution files. Maybe try regenerating project files.
Also, make sure you don't have compile errors.
why does this loaded resource go kaboom after one frame?
is there some way to get a permanent reference? or is getting it every frame not a problem?
It'll only go away if you don't do anything with it
i definitely do things with it
Show the full !code and explain what you mean by "go kaboom"
π 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.
public class PaniniCamera : MonoBehaviour
{
private Camera _cam;
private Shader _shader;
private Material _mat;
private RenderTexture _cameraCube;
private int _CameraCubeID;
void Start()
{
_cam = GetComponent<Camera>();
if (_cam == null) throw new Exception("This object is not a camera!");
_shader = Resources.Load<Shader>("Shaders/PaniniShader");
_mat = new Material(_shader);
_CameraCubeID = _shader.FindPropertyIndex("_CameraCube");
_cameraCube = Resources.Load<RenderTexture>("RenderTextures/CameraCube");
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
// _cameraCube = Resources.Load<RenderTexture>("RenderTextures/CameraCube");
_mat.SetTexture(_CameraCubeID, _cameraCube);
Graphics.Blit(source, destination, _mat);
}
}
This starts throwing NPEs after one frame on the SetTexture line
when i uncomment that line, it works fine
If the SetTexture line is the one throwing the NRE, then that means _mat is null. Chances are you're running OnRenderImage before Start runs. Change that to Awake instead
Where btw?
Ah yes.
in unity example code they have this in an editor script:
floatValue = EditorPrefs.GetFloat("FloatExample", floatValue);
if you have two different editor scripts both named "FloatExample" will this cause conflicts or does it seperate them based on the script
I need help for code simplification.
In my Code I have variables
"GameObject doorOne, doorTwo" and "Button btnOne, btnTwo;"
So I'm confused about how to make the code simpler if in my case I have 10 different buttons and 10 different doors.
It would look very stacked in my opinion if I listed 10 variables.
[SerializeField] private GameObject doorOne, doorTwo;
[SerializeField] private Button btnOne, btnTwo;
private void Start()
{
btnOne.onClick.AddListener(() => Door("1", doorOne));
btnTwo.onClick.AddListener(() => Door("2", doorTwo));
}
public void Door(string answerText, GameObject doorObject)
{
keypad.SetActive(true);
this.answer = answerText;
this.door = doorObject;
}
put the doors in an array
same goes for buttons
then in start just loop the array where each door index matches a button index
now you just need to make sure your two arrays are in the correct order in inspector
Like this?
{
int index = i;
buttons[i].onClick.AddListener(() => DoorSelect((index + 1).ToString(), doors[index]));
}```
if you need more complex answerText your array might need to be a key value pair where you have <GameObject,string> for your door array
yeah
if you use array not list then its .Length not .Count but you get the idea
Okay thanks. I will try it.
make it a singleton
assuming theres only one camera through the duration of the game
ehh more or less
thats the simplest way the other way is those that need to know can just find the camera via FindObjectByType<Camera> in Awake
now they hold reference to camera
in other words dont pass camera info around, only pass reference to the camera its far simpler
oh wait if its the only camera its already in the global domain via Camera.main
so ignore all i just said and use Camera.main where you need it
so i technically do have multiple cameras
ah ok are you using cinemachine
uh i don't think so xD
if you have multiple cameras is only one active at any give time
well... hmm
Thank sir, it work.
no they're both technically active, just different render textures
there will only be one rendering to the main RenderTexture
^ I'm having trouble rotating a cyclinder with a collider attached .... it looks like the collider is being rotated by its pivot point... i've tried the trick with an empty game object to create a new pivot which works for the mesh but not for the collider
ok one option then is make a CameraController which holds references to all cameras. make that a singleton then query the CameraController for which ever camera you care to know about and the controller gives you the reference of that camea so you have access to its data
okay lemme back up, sorry, singleton probably makes the most sense
it's more like a player
and there's only one player, and i need to pass around its information
are you rotating the child object aswell ?
like two rotations going on
i split it out so i'm just rotating the pivot_hurtbox empty game object
can you show inspector of cylinder
just use a singleton imo its the easiest approach a player is very different to a camera
are you certain the cylinder isn't being rotated aswell
yeah, i only used the word camera because i don't really have a player yet, only a camera controller and a camera
how 2 make dragging for 3d object? i need only x & z, i have an global y
yer as far as i can tell no
it's all being done in this animation
its not going to rotate correctly w/ scales being offset like that
if u need the scale offset use it as a child object and scale the child object instead. keeping the parent object scaled to 1:1:1
Hi, im just making my first game, i have stats like hunger, thirst, fatigue, and i just change these independently but with the same formula, i feel like its unoptimized an i see a lot of kinda repetitive code, so how should i handle stats like these?
make one function with your formula, so you can just call that function for each stat
I have a bunch of combat logic that I need to run both on my client and server (anti-cheat)
They're both C#, but they're two separate code bases
Any tips on how to manage this so my combat doesn't desync?
The code is very similar, but it's different in a few places as well, not sure if it's possible to make all the actual combat logic the same and then separate the extra stuff that is different
definitely a more #archived-networking related concern. I suspect the answers you'll get first ask you why its even separated in the first place. A majority of games really dont need this, unless you are literally making the next largest competitive game.
why wouldn't I want anti-cheat for a small game?
it's not a huge deal or perfect anti-cheat (probably) but some basics are fine not?
i was referring to the separate code bases
building a 2d game like terraria/minecraft. should i make each block/tile it's own gameobject?
well one is my client wich is unity and the other one is a UGS C# Cloud Code Module (the server)
my server is not build in unity
i see, still more of a networking issue or even try the unity multiplayer discord which has UGS chats
well it's not really a question about networking or multiplayer
I just wanna know how to keep two separate code bases synced
I think you are mixing up somethings in your head when it comes to syncing. You do not want to replicate the whole code base on both sides, but the returning values or predicted ones when it comes to network.
it has nothing to do with networking π¦
and yeah I do not want to duplicate the entire code base
I want to somehow make sure my combat logic remains the same on both client & server when I need to make changes to it
Again, the logic should happen on your client. The server should check if its allowed, but not dictate the logic of your game
or maybe you need to rephrase, what you are actually want to do. Combat logic sounds something for client for me. But that could be anything, as combat can be anything, so maybe you gotta explain a bit more
I'm generating a random seed on my server, which is saved on the server and then sent back to the client
The client then handles combat using that random seed
At certain intervals, for example after an item drop, the client will send a notification to the server that something happened
The server then re-runs the combat logic to make sure everything is ok and gives the reward
Ah, now things get clearer. So where is your issue. You dont want things to get desynced. But your datastream already sounds like its quite static and dependent on seeds, so your code should already know whats the latest state for both sides
the issue is that I have two separate code bases, one Unity client and one C# Module server
So I have most of my combat code twice
I want to prevent minor bugs sneaking into it when I change things that could cause a desync
Id say it is just bad practice to have it that way. I would refactor it before running into not updated code on one side because documentation was lagging to tell or whatever
If they are different code bases but doing the same thing, one thing is doing too much. no matter the codebase, language or what not
They're not doing the same thing.
The client is showing combat to the user.
The server is preventing cheating
Well, your messages are kinda confusing then. You have "most of my combat code twice" but "they are not doing the same thing"
Let's say there's a formula for damage in there somewhere: int baseDamage = 100
And I want to change that value to 105 but I forget to do it on the server
that's what I want to prevent
How?
In my 2D game, I have enemies that will follow the player when they detect the player. How can I stop the enemies from falling off edges if the player jumps to another platform? I want them to stay on the platform they're on
Decide who will provide those values and deliver them to the other side. Id say your server and database have the values and set them on the client. Client is only using them. If the client wants to change them, they have to send a request to the server and the server decicdes if its correct or not.
That makes sense for values, but what about actual code?
For example I have armor and % armor reduction and flat armor reduction
I first calculate % armor reduction and after that flat armor reduction
But I decide to change it around at some point, how do I make sure that logic is on both the client & the server?
What you're suggesting would have me execute all the code on the server. Which would then have to send back all the data to the client
Which is way too slow on the client and causes delays
Again, your server is providing values and predecting maybe. But if you have an item with armor and reduction, thats on client side. If you want to prevent the client to alter that armor stat, you can always sync now and then against the servers database of items for example. And saying "I decide to change it around at some point", what is IT? the default value? The calculation of the armor in general? In that case you are dreaming of a runtime compiled game...
and as someone else said before, this is like totally about networking and syncing logics. so maybe you get some more insights over there
Let's start a thread for this? π
I have an edge detector object infront of my enemy. I want the ray detection to go straight down so I can use it to detect if the enemy is on the ground. How can I calculate the raydirection ?
To get it to go straight downwards
Vector.down?
Which is basically just 0,-1,0
This makes sense, right? The ray direction would be starting at the EdgeDetector object and going downwards?
nope, the edgedetector is your origin of the ray and the direction is the direction. Now you create a vector in the direction of 0,0,0 to your detector.
My RayDirection is going 0,0,0 to my detector?
your direction is vector.down, and the origin is your detector
you are confused about position vector and direction vector π we all have been there
Yeah, the code I have. I should start the ray from the detector, and the direction will be downwards, correct?
yes, so do not subtract your detector in your direction. the direction is only a direction, up down, left right, whatever, but from the origin you set within your raycast
randomSeed = System.Convert.ToInt32(entry.Value);
entry.Value is an int64 from my server, why does a plain (int) cast not work?
Oooooh, I see. Thank you
Capacity of how long they can be
but then System.Convert.ToInt32 wouldn't work either? would it?
64 is like trillions, default int numbers to 33k or something. I am not sure if it will cry about it or just try to convert it and cut off, which would be bad for you. I do not think you need 64 in this case.
Why is it even a 64 bit value? I'm just defining a normal int, which should be int32, it's C#, not unity
int randomSeed = random.Next(1, 2147483647);
Guess the server is transferring it as int64 for some reason
https://hatebin.com/rivldfdqmq when i jump while sprinting even with a jumpforce of (50,5,50) i barely jump, its like i jump in place and not run jump
You'll have to show the entire movement code
I have this code for my enemies to detect when they are on ground. When they reach an edge, they stop, instead of running off the edge. Thing is, if the player goes onto the other side of the enemies, they don't try to go to the player, I think because the raycast for edge detection is detecting and edge, which stops the enemy from moving. Anyone have any idea how to get them to move again?
Is there a more reliable random number generator other than System.Random?
It's not producing the exact same results on my server and my client using the same seed.
The client somehow makes some values 1 lower and some the same
Could someone help me with adding a new inventory system to my project. i already made the new inventory system its just that i dont know how to add it properly
This is not all of it. No sprinting code for example. Just post the entire class. There's nothing in what you've shown that would explain the problem.
How can I flip a Ray Direction? I want it to face left then flip to face right
multiply it by -1 ?
Why am I getting this error? This is all written in Update()
because it's possible for RayDirection to not have a value
read the message. RayDirection is not always assigned to before you use it
your if / else if logic makes no sense
How so? It's dependent on a bool which is always true or false?
it should just be if / else, there's no need for else if here
exactly so why the second if ?
ahhh, I see. Thank you
There's still no sprint movement code here. Is sprinting done via animation? That will override force based movement
sprinting is just the Move() but the speed is 7 instead of 3 for walking 5 for jogging
Move() here
could i be helped trying to figure out why my onTriggerEnter dosent seem to be working
start by posting your !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.
are you in 3D? do you have a Rigidbody? do you have a Collider with isTrigger checked?
If the only thing different is the movement speed, all I can think of is the animation having root motion enabled and overriding rigidbody movement
there is no rigibody
So why no Debug BEFORE the if to see if it's even executed?
you need one for physics messages
read the documentation for OnTriggerEnter/OnCollisionEnter
thank you
you should not need someone to tell you to read the docs, you should be doing that automatically yourself
can someone help me? my regular jump suddently became super weak but is still affected by "Jumping power" but when I jump by using the Jump Buffer it works normally for some reason
!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.
ah
just without looking at the code your probably overwriting the velocity somewhere else before/while you jump
why do you have to get the parent object through the transform... sob
why is that a problem?
unintuitive
it's not that bad but it's just unintuitive
one would expect to be able to have a game object and directly access its children
true, you would expect the game object to have the parent. but the transform component deals with both parents and children, blame Unity devs for poor design choices
Basically, GameObject is just a holder for Transform, so you have to ask, why bother?
odd
it's weird that all objects need a transform tbh
but not necessarily a problem either
just kinda odd
no, transforms hold all the real info, what is odd is that transforms need a game object
huh, i see
if you think about it a Game Object is just a List of Components nothing more and one of those is the Transform
yes except Transform is special because it can't be removed
yep because without position rotation and scale an object is just a figment of your imagination
what if i want a figment of my imagination 
ScriptableObject
ah, lol okay
Hello, I wanna create a isometric game like Sims where players can create new rooms based on existing room models but I also want them to be able to edit those room models (add/delete grid cells). Is Unity Tilemaps suitable for this or do I have to generate my own tilemaps/grids programmatically?
yeah it can do that
Thanks :))
you need to look into asset bundels and addressables
Any recommendations regarding asset bundle Sir?
yes read the Unity docs
you want your users to edit your assets, so you make asset bundles or addressable packages provide them to your users which they can then edit and use in your game
guys I think I have a player controller problem.
π What do you expect from just posting this video in a coding channel?
!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 UnityEngine;
public class Thirdpersonmovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 6f;
public float turnsmoothTime = 0.1f;
public Transform cam;
float turnSmoothVelocity;
void Update()
{
// Check if the controller reference is not null
if (controller != null)
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnsmoothTime);
transform.rotation = Quaternion.Euler(0f , angle , 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle , 0f) * Vector3.forward;
controller.Move(moveDir.normalized * speed * Time.deltaTime);
}
}
else
{
Debug.LogWarning("CharacterController reference is not assigned!");
}
}
}
What have you tested yet and whats not expected to happen?
My sprite should be walk correctly but unfortunately it's not
When I pressed WASD It's worked normally but when I didn't pressed them My sprite was flown away
as you can see in the video
how do i make it so that as long as i keep pressing a button i keep moving ( for mobile unity 2d game )
idk what to use
like button.something..... idk something
What sprite? I only see 3d objects, or I am just blind
the capsule one lamooo
ofc, the only rule is to use a capsule as a player duh
Vector3 moveDir = Quaternion.Euler(0f, targetAngle , 0f) * Vector3.forward;
