#💻┃code-beginner
1 messages · Page 789 of 1
https://unity.huh.how/lerp/wrong-lerp or here it is again for your convenience
Applying lerp so that it produces smooth, imperfect movement towards a target value.
i tried implement the article way of lerping but i keep getting an error at
static float ExponentialDecay(float value, float target, float decay, float deltaTime)
what's the error
note that that method is intended to be put somewhere in your codebase and then called instead of a wronglerp call, rather than being pasted in wherever the wronglerp is
i have remade it and now it's on this line actually, sorry:
PlayerRigidBody.MoveRotation(Mathf.LerpAngle(PlayerRigidBody.rotation, FlapRotation, 1 - Mathf.Exp(-FlapRotationLerpSpeed * Time.deltaTime));
You should probably just use move towards as suggested at the end
ok, what's the error
also, is this in Update or FixedUpdate
Yes you are right , i just wanna know how to use lerp and not wrong lerp
that is irrelevant
Parenthesis mismatch
Is lerp never used for object movement ?
Yes
Lerp uses the original position before any movement as the first argument, destination as the second argument and how far you've traveled as the third argument (not your speed but more like.. your current progress).
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Thank you
The article illustrated Wrong Lerp and the Improved Wrong Lerp. The conclusion section would give the alternative solutions (lerp, smooth damp, move towards) https://unity.huh.how/lerp/wrong-lerp#conclusion
Imo, unless you care about the state of the t value (for reversal or to be specifically at any one point between the two points) smooth damp and move towards can probably do the same with less setup.
Ohh okay Tysm !
Alright , I have a better understanding of what it is for .
is there any way to make this blue gun sprite align perfectly?
sorry for the ultra late reply man, electricity went out, but its in update
Assets\Scripts\BirdScript.cs(34,26): error CS8112: Local function 'ExponentialDecay(float, float, float, float)' must declare a body because it is not marked 'static extern'.
honestly I don't see anything in here that looks like a "gun sprite", and you'd have to explain what "perfect alignment" looks like.
the thing that I'm selecting that's kind of hidden behind the draw order
doesn't sound like a code problem
true
which channel is better to ask this in
unity's UI is honestly my biggest opp so far
It is missing a )
Or at least your previous code was
This looks like a different error, show code
PlayerRigidBody.MoveRotation(Mathf.LerpAngle(PlayerRigidBody.rotation, FlapRotation, 1 - Mathf.Exp(-FlapRotationLerpSpeed * Time.deltaTime)));```
here yea go
You are clearly lacking C# basics
guess what
this is the code beginner channel
So you see this on the page:
of course there's gonna be beginners mate
oh sorry man
And then inside your method you'd call PlayerRigidBody.MoveRotation(ExponentialDecay(PlayerRigidBody.rotation, FlapRotation, FlapRotationLerpSpeed, Time.deltaTime));
Or something like that
oooooooh i see
So: cs static float ExponentialDecay(...) { ... } void Update() { PlayerRigidBody.MoveRotation(...) }
What's going on here is that you declare a helper method ExponentialDecay and then call that from your Update
You could just skip the helper method and do it inline (like in your previous code) but this is more readable
i see
sounds like you didn't copy the entire function
ah you already got answers
also mentioned it here #💻┃code-beginner message
Im looking at some code wtf does a ? mean in c# 😭
Ive never seen that b4
I have never in my life seen a ?
have you tried googling it
it's called a ternary, but just googling "question mark c#" should bring that up
Have you tried answering questions if ur gonna sit in this channel 25/8
second result, for me
this is a question that google can answer. if you have similar questions in the future, googling it would be much faster than asking here, and would give much more info
i know what it is
but i'm trying to tell you that there's a more effective way to get the answer you want
have you heard about the "teach a man to fish" analogy
researching your issue/question with google is also something you need to do before asking here, per the server rules #🌱┃start-here
i could give you the answer here, and then do the same when you come back to ask about other relatively basic/straightforward things
or, i could tell you that google is more than capable of answering questions like that, and save both you and me a lot of time for future questions
Knowing how to use search engines and documentation to find information about the solution to your problem is a very real part of doing professional coding. Can’t just always rely on people to help you.
been programming most of my life, literally most of my time is not spent writing code, its reading docs and books and papers
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I got at quick question.
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
we can't answer if we don't know what it is 😉
sry had to go for a sec while writing. So anyways, i have ver. 6.3 of the editor rn, and i wanna do create with code, which uses 6.0. Now my question is, if i should download 6.0 extra for this, or if i should stick with 6.3. Does it even make that much of a diff?
for relatively simple tutorials like that, there shouldn't be enough of a difference to matter
okay, thanks Chris
If I register callback on button during awake, how can I pass dynamic data that I will provide later? For example I want to change image and text on different element when I hover over a button
you could have a closure, in essence
presumably the thing registering the callback would know what it wants the callback to do, right?
you can use variables from the class inside the callback
Save the data in a variable. Show the data that's saved in the variables in the callback
e.g.
Sprite mySprite;
string myText;
void MyCallback() {
otherImage.sprite = mySprite;
otherText.text = myText;
}```
I really wanted to avoid doing it through variables 😄 But thanks
with UnityEvents on buttons you don't really have much choice
There's not really any other way to store data in a C# program. Anything else (like a closure) is ultimately just a variable wearing a trenchcoat
if you are registering via code i would just not use unity event
also you still can pass dynamic params though unity event
just make it a concrete class first then use that
UI is really driving me mad
You can have a new component with this data serialized and then have your own click events that provide these params
otherwise i would just sub with a function that already has ref to what you need, or make a closure to do it
thats C like void i main() int
I'm currently following a tutorial for player movement and rotation, why does rb.velocity show up like this
is the tutorial outdated
rb.velocity only works for the version below 6, in the latest version it is changed to rb.linearvelocity
your editor should also tell you this im pretty sure
Does rb.linearvelocity do the same thing
yes
yes it's the same
the code I shared is valid C#, not valid C though
!ide
If your IDE is not autocompleting code or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
guys can someone fix a script for me im new to unity
you have 2 classes called NameScript
yeah i know i tryed chatgpt to fix the scrip it just gave me 15 new errors
consider not doing that
didnt you also have this same issue yesterday?
just name them properly
yeah
and it was clear you are missing some basic fundamentals of c# and unity
open the file, change the class name to what it should be, save
and everyone recommended you watch some tutorials
rather than asking for help with very basic issues
oh but you did
yeah i watched that
you want people to fix your issues for you rather than actually learning, this isnt the channel or server for that
in this case it's a really simple thing tho 
i did try to fix it i couldnt do it i ask chatgpt and he gave me 15 new errors just like i siad
yeah, don't
chatgpt is not a replacement for thinking
chatgpt just won't really help you at this stage in learning
you gotta do things yourself
put some thought into it
yikes
aight
then... dont be
huh
good luck with.. existing on discord
see you in a year ig lol
aaaand there goes your account
yeah rip to your acc, if you so much as say "im age" even out of context the discord auto detection will actually block your account
to be blunt, you clearly don't have the maturity to interact in online spaces safely and productively
also google 13+ restriction, facebook 13+ restriction, etc...
you are way too young to be given unsupervised internet access especially on a social platform like discord
yeah
there is a reason for this and you arent rebelious or cool because you choose to avoid them, you are only putting yourself in actual danger
though keep in mind that turning 13 does not automatically give you that maturity
also this, in fact im of the belief all social medias including discord should not be acessible to children under the age of 16
from my own experience being a dumb 15 year old on discord almost a decade ago
i recommend to just stop relying on chatgpt to think for you. maybe consider stop using it altogether, and same with any other genAI/LLM stuff. start thinking and learning for yourself.
also yeah youre 12 and already relying on chatgpt to solve these kinds of issues..... this next gen might actually be cooked
where is Meina gladstone when you need her
Why you guys bullying a deleted account? 😬
deleted?
oh i guess they did actually get their account banned on discord bruh
no way
they have an automatic filter if you so much as insinuate you are under 13 years old
not even in that context
you litterally cant say "im number" in any context because the filter can just delete the account
reminds me of that "i'm [int] and my gf is [int] \n\n are our levels too far apart?"
Maybe they deleted it themselves when realized they're breaking the rules? Have some faith in humanity.
That would have been abnormally quick for a discord ban
I'm starting to get into some procedural generation and was looking for some high level advice. I'm likely just going to start with BSP and work my way through some other popular algorithms. Does anyone have any experienced advice on data storage strategies to go with (such as lists, dictionaries, primitive arrays?)
For instance, ive seen some tips out there were people stored the generated maps in both arrays and in hashsets, one used for rendering and one used for pathfinding. I'm just getting caught in the nuance of learning what data structures I want to go with.
Maybe start simple. Don't try to solve problems that you don't have.
hmmm, you're right, I should just do something until i hit a wall then revisit this. I'm looking ahead too much.
I still ahve to figure out how I want to preview generated maps too. I'd been just writing my own pixel data to a material but I thought perhaps unitys tilemap would be an interesting way to preview generated maps before i build a level out of the map data.
Up to you. Tile maps can provide an easy and cheap way to implement such a preview tool.
i want to make a cube look like a 6 sided die
and i want to use pixel art for the texture
how would i do that? could i make one sprite with all sides of the die, then use that as a texture?
if so, how would i set that sprite up?
this is a coding channel
How could i make an object be in two layers? I need it to be in Ground for player collisions, however i also need it in EditorObject for being detected by the editor camera, and making the box collider "include" the layer doesnt detect the raycast.
you cannot
is there an analogous fix to that
There's a few ways to do this. The simplest way is just model a die in blender and make it look like pixel art in the sides and just use that.
You can also make a texture for each side in any drawing tool and import each 2d texture in. Then make an object that is just a cube with texture renderers on each side with the texture you made set to them.
If you want more info you should go to the art chnnels
why does it need to be editorobject to be detected by the editorcamera
not really? you could use layer overrides maybe in some cases but it's not the same as what you're going for
(if your trying to ignore stuff in a camera usually people have a dedicated hidden layer)
because the camera detects only those objects in teh raycast, and not all of them are "ground" objects
i don't understand
could you use a tag for ground?
layer for ground is fairly common
im already using tags for other things and that wouldnt be consistent
why
when im in for example play mode, do i manually switch the layers of the objects?
why not just give it the ground layer
you could technically make a script for editor and switch it up
Generally (and ideally) nothing in your build scene/code should be composed for specific editor related code (one big exception is OnDrawGizmos though)
Well there would be some objects that in the editor should not collide with the player, so i wouldnt want them to be ground, but all should be detectable through the script i wrote that raycasts EditorObjects
hmm maybe i should be more specific, im making an editor inside of the engine
That makes a lot more sense ok
yeah sorry for the confusion
When you say Editor people are going to assume Unity Editor
yeah i forgot about that one
well does this mean i have to manually change layers when switching to playtest mode?
I don't recall if you were the other person doing this kind of thing last month or not but generally making a editor in unity is a big design pain because of issues like this
as your trying to re-create editor behaviour but using editor behaviour will overlap
nah i havent discussed this here yet
thats one way to do it
i actualy have mine working pretty well so far but switching to playtest mode is whats currently tricky
so i give each object like an OnPlaytest method that runs when the event for switching to playtest mode is called?
is this going to be a game or what? whats the purpose of this
Offtopic but just a heads up if you haven't ran into it, you can't make new Tags at runtime
well yeah i have the game just making an editor for it for the players, along with for me personally making additional levels
yeah dont worry im not planning to do that
i might as well just give it some guid
no, join a jam
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• ** Collaboration & Jobs**
Oh sorry
So just two cents for this editor thing, less a direct solution but just general vibe that might lead you to one
Try and avoid tag usage as much as possible since they are rigid at runtime, just use components and trygetcomponents instead
Generally honestly try and avoid layer usage as much as possible since you run into this double purpose issue, especially try and avoid editor related usage if you can
Swapping layers at runtime before and after you do specific things is probably a solid route but for other non raycast related things I'd also look into this as a solution tool:
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Physics.IgnoreCollision.html https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Physics.IgnoreLayerCollision.html
You can specifically ignore collisions between two colliders and between two layers. Since your likely spawning everything via code you should have easy enough access to these kinda references
Good thing about making a runtime editor is generally you probably have way more room to do cursed shit performance wise
Oh wow thanks for this it might come in handy depending on how jank my mechanics start to get
I guess id just store a variable that says if something should be ignored in collisions at runtime or something if i need to
does anyone have a shader for 2d sprite that reacts with 3d environment? (3d lighting, cast shadows etc
You probably need to use a MeshRenderer for that instead
With a basic lit shader
well there is a shader made by allendev that mimics octopath shader but it only work on sided, so if the sprite is behind a light the light won't illuminate the sprite. I thought there is a similar shader that works both side but I haven't found it yet 😭
is using meshrenderer extra work
Depends what "sprite" features you need I guess
Im not sure what would be the most straightforward way of animating it for example
Oh btw this is a code channel, you should ask in #1390346776804069396 or something
thanks! i couldnt find that somehow
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using UnityEngine;
public class ProjectileDamage : MonoBehaviour
{
// The damage that the projectile will deal on impact
public int damage = 20;
void Start()
{
// Destroy the projectile after 5 seconds if it doesn't hit anything
Destroy(gameObject, 5f);
}
public void OnTriggerEnter(Collider other)
{
// Check if the object we collided with has a Health component
Health health = other.GetComponent<Health>();
if (health != null)
{
// Deal damage to the health component
health.TakeDamage(damage);
// Destroy the projectile after hitting the target
Destroy(gameObject);
}
}
}
using UnityEngine;
public class Health : MonoBehaviour
{
public int maxHealth = 100;
public int currentHealth;
public Component Player;
//Player only reference
public HealthBar healthBar;
public GameObject uiPanel;
private bool isUIVisible = false;
void Start()
{
currentHealth = maxHealth;
//Remove line below if it's not a player
healthBar.SetMaxHealth(maxHealth);
if (uiPanel != null)
{
uiPanel.SetActive(isUIVisible);
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.V))
{
TakeDamage(20);
}
}
public void TakeDamage(int damage)
{
if (currentHealth <= 0)
{
Destroy(Player);
ToggleUI();
}
currentHealth -= damage;
//Remove line below if it's not a player
healthBar.SetHealth(currentHealth);
}
public void ToggleUI()
{
// If the UI panel reference is valid
if (uiPanel != null)
{
// Reverse the current visibility state
isUIVisible = !isUIVisible;
// Set the active state of the GameObject
uiPanel.SetActive(isUIVisible);
}
}
}
okay so when my enemy ai shoots a prefabbed projectile (that projectile has the script above ) it is supposed to deal damage to the players health script and it is not doing so. I will like to add that I did run the projectile script through Ai once as a last resort for the projectile script so thought i should mention it
but my main question is why is it not dealing the damage to the health script of the player once the projectile hits the player?
make sure the OnTriggerEnter is being called, use a Debug.Log
Does it work when you press V?
yeah the press V to take damage works so to my knowledge its something with the projectile script but i could be wrong
public void OnTriggerEnter(Collider other)
{
Debug.Log("Collided with: " + other.gameObject.name);
// Check if the object we collided with has a Health component
Health health = other.GetComponent<Health>();
if (health != null)
{
// Deal damage to the health component
health.TakeDamage(damage);
// Destroy the projectile after hitting the target
Destroy(gameObject);
}
else
{
Debug.Log("No Health component found on: " + other.gameObject.name);
}
}```
added the Debug.Log
so can you see the message now
and nothings being posted in the console when the projectile hits
ok then the OnTriggerEnter is not being called, make sure you fulfill all requirements for that
you need to mark the collider as "isTrigger" on the target objects the projectile hits
Ahhhh i see now
it works now
tysm
i just added the istrigger to the projectile itself so it can be multipurposed later on
ideally you would not have isTrigger on your objects, you would then check for OnCollisionEnter instead. isTrigger is for obbjects that would not collide with anything, for example coins that you collect but you dant want collisions to occur
I'll keep that in mind and now i get to try adding an hp bar to the enemy and letting the player shoot something back lmao
Hi, anyone has a tip on how to manager a multi ending game? I thought using bool like:
has player talk to
Has player choose to…
Then when reaching a posible ending, i check if those bool are true but it seem like very barbarous 😅
bool is not good
try to make special gameobject on scene
an emnpty gameobject for each case
and if a player did something you enable the curret gameobject
Yo yo yo
What is that game engine goodo or smth I low key forgot
Nvm it’s Godot
Can someone send me invite link pls
And how is that better than using a bool (or any other types)?
You could look into enum Flags, which allows you to store multiple "bools" in one enum value
One for each bit, 32 bits by default
Do u know godot discord?
Jesus man just google it
it is like going to mc donalds and asking for the direction to burger king
i am not a fan of either btw
bool are not clean and give a lot of error
but enabling and disabling gameObjects doesnt sound like a perfect soloution
in fact it sounds like a bad pattern
it working for me so idk for the rest
i was coding hack before so i dont like all this unity things
i only know how to reverse it
What does it mean that a bool is not clean?
Bro what...
in what contex,where did you hear that
So you admit that you reverse engineer unity games?
Look up..
oh yeah that
Few comments above
bool or enum would be the first choice for this, how you handle it depends on you
or some kind of state machine would also solve it
not unity
unreal
but it the same process
with the ram allocation and all
this message is not sourced from knowledge
there is just no UObject on unity
yeah ik
just for my experience

It seems that you have no experience to be giving those suggestions then
if you don't know something though maybe don't give opinions and/or help then
im just tryinng to help
no vc's here and this is a unity discord
no one is saying that
idk am giving up yall true ig
your allowed to not know things just don't misinform others because that's counter productive
would you like being told random stuff if you asked for help
This gotta be ragebait
i only trust myself lol
ok man
He was also calling people stupid for putting their logs in #💻┃unity-talk , very kind of him
yeah he is stupid
that kind
Alright bro just drop it its okay
when he will know he is stupid he will change
Can you stop this noise, thanks.
saying the truth dont make noise
but aigh
mod got all the right on this virtual space
!mute 1074987335348932609 2d Insisting on getting the last word in doesn't make your point valid. When you return, have a better attitude.
@grap_off muted
Reason: Insisting on getting the last word in doesn't make your point valid. When you return, have a better attitude.
Duration: 2 days
yikes
Hi guys. Im creating the first game drag&drop and i have code here
https://pastebin.com/vDssWguv
and I want the cube not to go beyond the camera and for it to have a distance from the mouse to see where you want to put it but the ratio changes I don't understand why I want it to be the same so that the cube has a small distance from the mouse and as you can see the code doesn't really help so that the cube doesn't go beyond the camera How can I improve my code?
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.
Hello.
I am making a worms clone.
-
I have an sprite and I put 2d polygon collider on it, it makes this collider. It doesn't fit the sprite. What to do?
I got the destruction part working.
I move player but when its like this, its controls gets inverted ? right now moves it upward but slowly and left downward.
how to upload code?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://paste.ofcode.org/3apQyBwcQ3VTNUnvdgMWdPv
Here are the two scripts, one for the map/terrain and other for movement.
- On edge of a point, it just fights. snaps the the above one then below one.
Please see in code I snap it so that the circle is stuck to the ground so it can climb steep edges.
I took a quick look and SnapToGround is moving a rigidbody with transform.position. You should not move rigidbody objects with transform, it results in weird behavior.
Try rb.MovePosition instead
same with transform.rotation -> rb.MoveRotation
How strongly is it advised to finish a Singleplayer game first before even attempting anything multiplayer, I'm not wanting to make anything super advanced, just to be able to simply connect peer-peer no dedicated server stuff etc. I'm aware that it's a bit of a nightmare to convert Singleplayer projects to multiplayer, just wondering how feasible it is to make something very simple that has rudimentary multiplayer
(if this is the wrong place to post this I apologise)
Making something very simple and rudimentary is not terribly hard, making something polished that other people might want to play is
So it all depends on what the actual goal is
Literally just something to mess about with a friend
Would be happy enough to learn how to get a room in which two players can walk around/be directed to move in for the moment but wasn't sure quite how formidable netcode is
There are plenty of tutorials for that, you could just browse through one and see how it looks like
Fair enough, il have a look then, just wanted to ask beforehand as have seen a lot of recommendations to entirely avoid multiplayer for any purpose before finishing a Singleplayer project
I haven’t use it a lot like only one timd but so can i extend it to bigger than 32bit ?
Or i split them into multiples flags then check them all ?
Yes you can use any integer type
For example cs public enum MyEnum : long for 64-bit
Note that unity only serializes the default 32 bit ints
oh thanks you, it is so much easier and faster i think than just compar all posible bool one by one
i made and finished my first unity game, what should i work on now?
What kind of answer are you hoping for?
This is a coding channel. #🖼️┃2d-tools
i'm a beginner and i'm hoping for an answer giving me a game idea that could be perfect for my 2nd game, i have no idea what to make
You came up with your first game, you can do the same for your second. 🤷♂️
Not sure why people need other people to tell them what to do. You're dedicating a lot of time and effort to make things, it shouldn't be random people on the Internet telling you how to spend it lol.
Anyway, make Flappy Bird.
that was my first game 😭
Pong
Good luck
Search 20 games challenge. Its a nice list of progressively harder games to make.
if you dont have any more ideas you can also make smth like minesweeper, snake, doodle jump
what are these and how to remove them?
CodeLens
that's the syntax error detection right?
it just tells u info bout the code
noo.. its seperate from that
Intellisense is what shows broken code/syntax
My alpha is still 255 after setting it to 50. Is there a work around for changing it
I unticked this, it kinda worked
thank you
IntelliSense
- What it is: Your editor's smart assistant for code completion, parameter info, and basic syntax checks (like a red squiggle for a typo).
- Focus: Real-time help with writing code correctly and quickly.
CodeLens - What it is: A feature that displays information directly in your code editor, above methods, classes, etc..
- Focus: Contextual history and usage: "This method was changed by John 3 days ago" or "This class is referenced by 15 other files".
it takes a value between 0 and 1, unless you use color32
unsure about that one.. this is where ifound it
edit: this is vscode
👇
go into file>pref settings or w/e and then searching for Code > Codelens
oh right, forgot about this
Thanks
Hello
yea the pins in here have lots of sources
I am very new to unity, I only know how to dump a plane and assets, how I learn with you all
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
this server isn't really hand-holdy.. but we will help out when-ever
its best u venture off on ur own.. and try learning.. yourself and coming back to this server for specific help
say u dont understand a certain component.. or a script.. u can come and ask specifically to explain it.. or ask follow up questions 👍
Hey guys I’ve got a question. How am I able to detect to my player is taller than a game object yk?
Any ideas of that
basic math 😉
I thought of maybe doing a sphere ray cast
Just seeing if there’s nothing, then I’m taller
Oh fr?
public Collider playerCol;
public Collider targetCol;
void Update()
{
if (!playerCol || !targetCol) return;
float playerHeight = playerCol.bounds.size.y;
float targetHeight = targetCol.bounds.size.y;
if (playerHeight > targetHeight)
{
Debug.Log("PLAYER TALLER");
}
}```
if they are the same size (scale) u can use the bounds of the renderer or the collider
use a collider/trigger/raycast etc to get the transform of the other object
then the comparison should be relatively simple
using UnityEngine;
using UnityEngine.UI;
public class EnemyHealthBar : MonoBehaviour
{
[SerializeField] private Slider slider;
[SerializeField] private Camera Ecamera;
[SerializeField] private Transform target;
[SerializeField] private Vector3 offset;
public void UpdateHealthBar(float currentValue, float maxValue)
{
slider.value = EnemyHealth.EcurrentHealth;
}
void Update()
{
transform.rotation = Ecamera.transform.rotation;
target.position = target.position + offset;
}
}```
using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
public GameObject Enemy;
public EnemyHealthBar EnemyhealthBar;
[SerializeField] float EcurrentHealth, EmaxHealth = 100;
private void Awake()
{
}
void Start()
{
EcurrentHealth = EmaxHealth;
EnemyhealthBar.UpdateHealthBar(EcurrentHealth, EmaxHealth);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.V))
{
TakeDamage(20);
}
}
public void TakeDamage(int damage)
{
if (EcurrentHealth <= 0)
{
Destroy(Enemy);
}
EcurrentHealth -= damage;
EnemyhealthBar.UpdateHealthBar(EcurrentHealth, EmaxHealth);
}
}```
apparently EnemyHealth.EcurrentHealth is inaccessible due to its protection level and im honestly a bit lost lmao
been fighting this health bar for a while now
cuz its private
might wanna make it public and get rid of the serializefield?
also you need to turn EnemyHealth into an actual reference
tbh didn't know serializefield was private , I'm new to this if you couldn't tell lmao
using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
public GameObject Enemy;
public EnemyHealthBar EnemyhealthBar;
public int EmaxHealth = 100;
public int EcurrentHealth;
private void Awake()
{
}
void Start()
{
EcurrentHealth = EmaxHealth;
EnemyhealthBar.UpdateHealthBar(EcurrentHealth, EmaxHealth);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.V))
{
TakeDamage(20);
}
}
public void TakeDamage(int damage)
{
if (EcurrentHealth <= 0)
{
Destroy(Enemy);
}
EcurrentHealth -= damage;
EnemyhealthBar.UpdateHealthBar(EcurrentHealth, EmaxHealth);
}
}```
using UnityEngine;
using UnityEngine.UI;
public class EnemyHealthBar : MonoBehaviour
{
[SerializeField] private Slider slider;
[SerializeField] private Camera Ecamera;
[SerializeField] private Transform target;
[SerializeField] private Vector3 offset;
public EnemyHealth Health;
public void UpdateHealthBar(float currentValue, float maxValue)
{
slider.value = Health.EcurrentHealth;
}
void Update()
{
transform.rotation = Ecamera.transform.rotation;
target.position = target.position + offset;
}
}
I did it :D
serializefield was private
This doesn't make sense. SerializeField is an attribute and has nothing to do with protection levels.
the default access modifier isprivate. That's why your field is private
yup, SerializeField is a private variable in sheeps clothing (public) edit: if you just do [SerializeField] private float myFloat or [SerializeField] float myFloat <-- same things
it just exposes it in the inspector and makes it editable.. (still private behind the scenes)
the default access modifier is private. That's why your field is private
☝️ this
elaborate, what line? I fixed it but where was it an issue before, for future reference.
[SerializeField] float EcurrentHealth, EmaxHealth = 100;```
These variables are private because there is no access modifier
Not because of SerializeField
basically
float EcurrentHealth
is the same as
private float EcurrentHealth
They would still be private without serializeField:
float EcurrentHealth, EmaxHealth = 100;```
but once you made it public there was no point for serializefield being there anymore so thats why i told you to get rid of that as well
aye on the bright side I figured out like 9 other errors alone before this one 🤣 I'm learnin slowly but surely
thats what im talkin bout
Hello quick question. So I want to detect if something enters a collision with a box collider, so I should use OnTriggerEnter. But the thing is that I have the script attached to a different game object, so if I do OnTriggerEnter, it will try to find the box collider of the game object my script is attached to, but I can't do something like myboxcollider.OnTriggerEnter . So what should i do?
public void OnTriggerEnter(Collider other)
{
// Check if the object we collided with has a Health component
Health health = other.GetComponent<Health>();
if (health != null)
{
// Deal damage to the health component
health.TakeDamage(damage);
// Destroy the projectile after hitting the target
Destroy(gameObject);
}
}```
can always do a boxcast or checkbox or overlapbox, might be better or worse than a trigger depending on what exactly you're trying to do though
idk if it helps but i did something like that with a projectile
Oh wait i might be dumb
You can also just make a script which raises an event / UnityEvent when OnTriggerEnter fires. Then anything can subscribe to it can run a callback.
Oh okay Yes so this just wouldn't work because my script is not attached to the collider
Yes You are right i just wanna know if there is a way to do it in the same script
Not as far as I’m aware.
okay thank you :)
Yeah you can’t natively get a callback for OnTriggerEnter from another GameObject — only for this one.
AFAIK
alright !
I just want to create a hitbox that detects a player so that the NPC can pivot in front of the player. Maybe i should use a RayCast instead ?
Can you try describing this a bit more? I’m not really sure what you mean
Like a bot field of view
For enemy FOV it’s common to just use DotProduct. You could try that
That will tell you how “much” the enemy is facing the player
Okay thank you I have no idea what it is but I will have a look at that :)
You’re about to learn some useful concepts then 🙂
hello! Im applying a torque on the y axis using addTorque and the x and z axis are having no torque applied. in addition, the rigidbody has freeze rotation on x and z. even so, the other axis are rotating and im unsure why
same issue for relative torque
Please stop cross promoting this. If you have a tutorial to share, you can post in #1179447338188673034
Also read the guidelines for posting in that channel.
is it due to the intermediate axis theorem
Hi I’m making a small 3D first-person game in Unity but I’m stuck on something I can’t manage to add fog that starts at around 5 meters like in the screen, I’ve looked for tutorials and stuff but I couldn’t find anything
if anyone can help me
ty
it might help to se your set up and understand how you have built it and rekomend fixes and ways to improve :3 i am myself not a good coder
I haven’t started any big project yet I actually started with this but I can’t manage to make it work
so are you using the effekt sistem or a block half sethru
system effect I think
idk
with rendering > environment and fog but nothing
so for fog i usaly do this https://www.youtube.com/watch?v=RBI9hQWD_xY
Hello everyone. In this video I will teach you How to Add Fog in Unity. This is one of the ways to Add Fog in Unity. If you want to make a moving Fog please tell me in the comments and I will make another simple video for that.
The assets used in the video: https://assetstore.unity.com/packages/3d/free-low-poly-pack-65375?aid=1011lkXBB
#HowTo...
u dont understand i want the fog but around the player like this
ok so i can garanty as i have almost 0 knolige using effekts so i may make a error \
o so around the player not spawn?
Basically, it’s like you’re in a very dark forest where you can only see about 5 meters around you, and after that it’s just black. You know what I mean?
if player some may shout but make a big sirkle no kollition and add t player in the middle and make the sirkle a child of the player and sorry for misspell missing some keys
then have no ambient light and a point light follow the player
thats not fog its just controlled light
I already tried that, but when I move my camera, it turns completely black
Are you using a spotlight or point light?
let me turn on my pc ill tell you
XD
both doesn't work
If lights dont work you have done something very wrong
please go learn the basics of unity
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
That doesn't sound right. Does it have any other components/scripts? Something else is probably doing it
Or are you doing something transform-related with the rigidbody (parent/child, rotating, moving)?
Don’t you have a specific tutorial for what I’m looking for?
The lighting section in the creative core course: https://learn.unity.com/pathway/creative-core/unit/lighting/tutorial/get-started-with-lighting?version=6.3
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
Howdy, I'm trying to setup a Node (in 3d space) for specific location where multiple units can go, and I would like it to work in a way that - as more units arrive at that node, they will get arranged in "esteticaly pleasing" way.. always forming n-gon .. sort of like on the very well made picture of mspaint..
As I don't know theroretical maximum of units at single node, instead of creating each scenario by hand placing empty game objects...My thoughts were to make a circular spline with expanding radius based on amount of units present (as a child for example) along which I would distribute those units in equaly distant matter. Therefore if there was only one unit present, radius would be barely noticable, but as more units would arrive it would grow. Does that make any sort of sense? Can someone point me atleast towards some way/name of what I'm trying to achieve?
nothing that wold result in a roll force
if i disable the torque in the y axis it wont roatet it
at all but then when i apply torque in just y it rotates in all directions
Can you show the inspector
Is it a child of another object and/or does it have children with any components?
this boat itself has no parent however it does have children
the boat is an empty gameobjec.t the body is the actual gameobjrct with teh bollider. then the rudder is an empty which si the pivot. the fin is the actual fin.
i apply the torque on the y axis to the boat becuase it has the rigidbody.
fin has box collider rudder nothing
- this is a code channel
- you need to fix the UVs for the model or edit the material to set the tiling you want
Since that looks like it came from a prototype texture asset, they typically expect you to use their triplanar shader they provide, or your own triplanar shader.
ah I see thx
any ideas?
Does it still happen if you disable the fin/its collider?
that fixed it
but why
😭
I bet you are rotating the fin with transform
yeah im changing the eular angles
What if you disable that code but enable the fin?
Rigidbodies dont work well with transform modifications, be it child or not
hii , me again, does unity have a system of auto scrolling ? with the textmeshpro?
i cant rlly test it because i built it around an interpolator but ill take ur word for it
thats very annoying tho
whats the solution to this
use quaterniosn rotations?
Probably a Joint
quaternions wouldn teven fix it?
No, the issue is that you are modifying the transform
and thats not good with rigidbodies?
No
do u know why?
that way i can alleviate future issues
and why disabling the box collider fixed it bc i didnt think that had to do w transforms
Because the physics engine has its own way of moving rigidbodies/their transforms
A child with a collider is "part of" its parent rigidbody
hm i see
When you disable it, the rigidbody just ignores it
Transform rotating a child with no collider is fine
got it thats strange. thank you!
im trying to read through the physics engine source code to understand why and it seems like the a child part changes the mass center. the file nprigidbody.cpp updates the balance point and the spin axes immediately. then if you move that child part the spin axes tilt away from the world axes. the integrator in dybodycoreintegrator.cpp takes the torque and applies it to the tilted axes. bc the axes are tilted the force makes the object spin on multiple sides at once. so like the engine sees a lopsided shape and acts accordingly.
thats what im able to parse from it
that was my first suspicion abt the shape being changed due to the collider, but when i debugged the center of mass, it didnt change in the console so 🤷♂️
I think u talking about the text box
Sorry
I mean “scroll view”
oh i think yes like if the text is too big in the case , it will scroll down and the user can scroll up down. if it is too long i will just cut the text I think
TMP text can use content size fitter or layout groups to auto set its rect size
you mean scroll Rect ?
tbh i have not needed this setting. You can make do with the text as a scroll rects "Content" with a content size fitter to set the width /height
Layout at top right and set it to default
Pretty sure there's a key bind but i forgot it 😂
i just found out its shift + space but thank you
Where it says "🎮 Game" to the left, double click that tab
this error
!input
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.
the error tells you what to do, too
open "other settings" and scroll down to active input handling
I made a cube that rotates randomly, and now i want it to slow down and land on the face that is closest to the ground plane. how could i do that and find out which face it's sitting on?
the cube is a d6 die and i want it to stop rotating after a while and land on the face closest to the ground
break that problem up into smaller tasks and figure them out one by one
loop through the 6 directions of the Transform (up, left, right, down, back, forward) and see which one has the smallest angle difference (or dot product, if comfortable with that) with the global up(or down) vector
right i'll try that
if you search up "roll d6" in google, it shows you a virtual dice roll. How is google doing the rotation for those dice?
It's precisely how I did it when I solved this exact problem 6 years ago
right now, my die just rolls in a rnadom direction
ah nice!
but google's version rolls around, not just one direction
Google's thing looks like a canned animation that is always the same, or maybe has one or two variations.
it's just showing a random number in front of it at the end of the animation
there aren't even numbers on the faces as it rolls
right. im just wondering whats the best way to simulate a dice roll in my game. it needs to be fair
You'll need to explain what your constraints are exactly
right now, i just pick a random direction and it rolls for a bit, then slows down
there is no ground in my game. its just a 2d game with a 3d die in it
the die needs to rotate randomly without moving its position
one option is to do something similar to what google is doing - show some kind of animation and then just pick a random number to show.
then land on a side
that's kinda how Baldur's Gate does it too
yeah i could do that, but im now sure what exactly they are doing to have it roll in that way. its not rolling in one direction. it changes direction during the spin
yeah baldurs gate does it, but that die moves around as well
i want a stationary die to roll in place
it's an animation
you could record it manually, or you randomize the rolling direction over time and then have it stop
ah right true
i'll have to try randomizing the roll direction
im thinking based on what the current direction is
so say its rolling upwards, the randomness will make it roll slightly differently from upwards
you could also set random linear/angular velocities and have it play out physically (then detect the top face with what praetor mentioned)
like with nintendo's yahtzee
there is no ground. the die is floating essentially
but that might not work out with your intended UI/UX
and i dont want to move the position ever
(not a suggestion, just a train of thought) i wonder how jank it'd look if you simulated it physically and just had a camera following it to make it look like it's in the same position (without showing the geometry it's colliding with)
yeah, but with that, the camera would move when it shouldnt, at least for my game
nah, a separate camera just for the cube
ah right haha
How can i learn input system in unity ?
there are many videos and all of them teaches different methods
there's a lot of ways to use the new input system
options, in no particular order (because i don't have the brainpower to sort them right now)
InputActionReferenceas a serialized field, poll thatInputActionReferenceas a serialized field, subscribe to thatPlayerInputcomponent with messagesPlayerInputcomponent withUnityEventsPlayerInputcomponent with C# Events (not sure what that entails)- Generated class, poll that
- Generated class, subscribe to that
this list is not exhaustive
script system is good or inbuilt one?
i mean i was using my script to move my player and i saw then there is another way to do it too, then im now asking which one is good and easy ?
i was using my script to move my player and i saw then there is another way to do it too
What?
Are you asking about... another movement script? Or another scripting engine? Or something else?
You must code (use your script) your player movement. the new input system is just a flexible, event-based approach that allows you to easily modify and expand the handling of user input . . .
so input system isn't wort it?
just " inbuilt input system "
i was just copying code monkey's tutorial and i still not working so im lost now
What are you talking about? Best lookup a tutorial. You'd setup the input system then communicate with the system through code
there are many videos and all of them showing different things
The new (not so new anymore) input system should be the same as always.
You'd simply setup the system for buttons actions etc then communicate with the input system through code
yea and yt videos making these things more complicated as everyone showing different ways , i tried to copy code monkey's code and the way he does things but even after setting up everything , its just not working
What Chris would be referring to would be whether you'd poll or not etc
Normally you'd link the tutorial you're following, indicate the step you're at (relative to video time) and provide information on your scene/hierarchy/script
this is what i was watching
here all he did is that when he presses spacebar and then console returned the "Jump" string 3 times
i copied and still not working
Have you setup the input system like he has? (it may have been done in some other video)
have you set the input handling
have you set the unityevent up
this is what he have done and i copied him
your actions have not been saved
u mean to save asset right? i have clicked it and still not working
you've set the right function in that unityevent, correct?
check the input debugger to make sure your keyboard input is being received by the input system
how to check
open the input debugger, there's a button on the player input
open the keyboard menu
see if your input is being received
thanks its working now
Can anyone help me find some good tutorials for coding c# for game development
As most tutorials just tell you what to do but why
there are some pinned in this channel, as well as some by microsoft just for c# in general
Ok thanks
how do i make it so my player doesnt shift into stairs the character shouldnt be able to go upwards (cant go upwards while heading straight) while facing at an angle
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.
this is my collider setup
and my rigidbody setup
it is unclear what you want, could you explain again
its a bit hard to explain i might take a vid of it
the player should stop after coming up to the step (happens near the end of the vid)
you want to be able to go upstaris only when facing straight forward
if i understood correctly
you´d have to get the angle from your player to the stairs normals
i want the player to go up small steps, but it shouldnt be able to get up the step i was trying to get up
could we see the code for moving the player
looks like you are transforming the player instead of using physics
this is the code
im using addforce to move the player
you could place bigger colliders manually if you only have a few of these steps of course or are these this procedurally generated steps
theyre manual but i feel like that would be a bit jank in general honestly
i want something that would work universally
i see
it is straight forward, how to detect high steps. you could simply use a raycast from the heigth of the player knees forward, but how you prevent the player from going forward could be tricky
okay i figured out exactly what's happening
when i mfacing exactly straight, the player automatically stops (expected behavior)
but any sort of deviation messes up
Could I ask how people got started out in unity game development it just seems so complicated and hard to understand
this was actually a problem with how my stairs were levelled lol
was a placeholder anyways
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
start here
Thanks 🙏
guys how do i add fog?
Use Unity's fog system
. Also not a coding question.
use charactedr controller
How can I do this in Unity? Like I can only see about 5 meters around me and after that everything is black thanks if someone can help me
this is a code channel, try #1390346776804069396 or #💻┃unity-talk (maybe postprocessing? i don't know which direction you'd go)
They asked like 1 day ago anyway so they just didnt like the answers given 😐
this is a code channel
please don't advertise your question
you're not gonna get anyone from here anyways. only code nerds here
if someone knows they'll be in that channel
In the project assets window, how do I make a json file?
Do it externally with your OS file explorer
ok
does anyone maybe know a better way to handle seperate sound cues than what I'm doing here --> https://paste.mod.gg/lsdycrehmxec/0 ?
A tool for sharing your source code with the world!
cuz I feel like this is a really unnecesarily drawn out way of going about it lol
you should use only one AudioSource
then use as many AudioClips as you want and then AudioSource.PlayOneShot(audioclip);
i just made this, is this a good way to make movement?
public class Player : MonoBehaviour
{
public Rigidbody rb;
public float PlayerSpeed = 5f;
private void Update()
{
Vector2 InputVector = new Vector2(0f, 0f);
if (Input.GetKey(KeyCode.W))
{
InputVector.y = +1;
}
if (Input.GetKey(KeyCode.S))
{
InputVector.y = -1;
}
if (Input.GetKey(KeyCode.A))
{
InputVector.x = -1;
}
if (Input.GetKey(KeyCode.D))
{
InputVector.x = +1;
}
InputVector = InputVector.normalized;
Vector3 MoveDir = new Vector3(InputVector.x, 0f, InputVector.y);
rb.linearVelocity = MoveDir * PlayerSpeed * Time.deltaTime;
}
}
it is not good no make use of input axis instead
oh oki
wbt the actual methods themselves though
this
cuz I'm going to have to add a lot of different sound cues and I don't want it to get rly messy
methods would be called nearly at the same time, i dont see any cue here
also inside the Update you are calling the method every frame, i dont think that is what you want
if you want some kind of delay or cue you could use a Coroutine
Why don’t you just play the AudioSource where you set the bool to true? Then you don’t need to be checking it with Update
isn't that already what I'm doing? or like wdym
Your bool playLeftDoorSoundCue in the if clause
wherever you've set playLeftDoorSoundCue = true; just do playLeftDoorSoundCue(); instead
you have significant spaghetti here
these methods basically just do 1 thing that can honestly be inlined
oh sure
You also have a method and bool with the same name
making systems more modular is nice, but at some point it becomes incoherent
smth like this then --> https://paste.mod.gg/ijsdemnxxorj/0 ?
A tool for sharing your source code with the world!
i'm extrapolating a lot here, but do you really need separate AudioSources for something like this? you could have a single audiosource that's configured (spatial/volume stuff) and just play one shots with separate clips instead
Yeah you have several steps for something that could be a single line
won't that cause issues if multiple audio clips need to be played at the same time though?
or like how does this work
that's why i said to play one shots instead of just playing the clips directly
Anyone got a tutorial on how to do something similar to source's bodygroups? To toggle a model part on and off?
you mean just a gameobject that you toggle on and off?
So make a prefab where different pieces of the model are separate gameobjects?
how would I ensure the parts go where they need to relative of each other?
if you export from blender then the pieces are separate already if they're separate in blender, so you can just toggle the pieces on and off inside unity.
not sure how or if rigging works in this case though
Oh so they will already be separated when importing?
yeah
Is unity going to make a .meta file for all jsons or something?
every asset, including json files you import into the project will have an associated meta file
every folder has a meta file as well. these are features, not bugs
ok
ok so i can't figure out how to add more inputs to my setup. I remember having a list of different things and now it's not there
Hay so I'm just having a general issue with something.
So I have on script called LedgeTriggerScript that just triggers if the player is in the ledge trigger space. Now I just need to set up a way for that script to tell the PlayerMovement script that the player is in a ledge trigger space, so I can it can do a clime movement.
This is in the PlayerMovement
and this is in the LedgeTriggerScript.
You have to change the list size but you should use the new input system instead of the old one
how? I know i seen it but i can't find out how to get back to it
try the quickstart guide: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.17/manual/QuickStartGuide.html
You call a function on PlayerMovement to either enable/disable the functionality you want
i's not showing the new stuff
Is it enabled in your project? (player settings > other)
!input
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.
it just shows this thing
and it is selected
What unity version is this?
the guide wants you to setup a global input action asset but that is not required
2019.4.28f1 Personal
try to update your packages and check for compile errors.
it says up to date still
Ah you need to upgrade to the last 2019 version so you can get v 1.12
Or upgrade from 2019
1.0.2 is ancient
how would I do that?
add a function to your class and call it. That is basic c# which you should already know
public void SetClimbState(bool enabled){...
//Elsewhere
pm.SetClimbState(true);
you install a different version...
thats just selecting from your currently installed ones
also why tf are you on ancient hub too
god damn
haven't messed with it in a while
step 1, update hub
step 2, visit download archive to get the latest 2019.4 patch version (2019.4.41f2)
https://unity.com/releases/editor/archive
how much is going to break if i upgrade?
Very little to nothing but you should use source control so there is no risk
otherwise make a full backup beforehand
when you say "else where" do you mean in the same file or a different one.
Then you'll need to read them
Start at the top
i mean where you want to call the function. You really should read up more about c# to understand these basic concepts better.
Experience works better for me.
anyway I'm still having an issue. my playermovement script doesn't seam to like what you gave me and I get this error.
Compiler Error CS0103
It was just an example
You need to define the function and call it on the instance you get via GetComponent
this makes no sense
OnTriggerEnter is something unity calls via physics / trigger enter not something you call manually
a ledge grab system kinda over scoped for someone who doesn't know basics of C# / calling methods from other components
if you only have a bool that controls "IsLedgeGrabbing" you would use a method or set the field yourself
why OnTriggerEnter(true) was ever a thing? their example did not do that
OnTriggerEnter is what my ledge detection method is called. It something i found from some tutorial a while ago.
OnTriggerEnter is a Unity monobehaviour method
did you mean enable OnTrigger ?
if they mean the bool then yes, but thats not a method
also for clarity most bools are prefixed with Is
i have never see someone put a true on OnTriggerEnter.
my bad, i was talking about the option in rigidbody
nothing you did, I meant their bool
okk
oh i think i will do it too
i don't think i am adding Is as prefix on my bool too
its not a hard rule but it helps identify a bool, if you think about they are simple states
IsSleepy IsCrouching etc.
On prefix usually for Events
OnHit etc.
hahaha
anyway OP should probably scale down the scope until they get better at C# basics
i am not joking if you think so, i am i think still a new and i need to make a doc so my project can be more clean
hmm , damn i forget what i was coming for :/
this PDF goes over some of the stuff I mentioned
thanks
I mean just for the future, you don't have to refactor unless it really messes with your clarity, the important part is if YOU understand your own code today, tomorrow and months/years from now
certainly helps if everyone is on the same page, and if you follow "standard" naming practices then its easier than making your own, but you can certainly do the latter too
well, if they need to know anythingj, they will ask me anyways event if the code is
in add(x,y)
return x+y;
Alright I got it working thanks for the help.
Curious now i know its not really proper but how much would a workplace be bothered if i named my variables starting with a capitol ie int MyInt instead of int myInt been doing it like this since the beggining since the first ever youtube video i watched on programming had it written as such.
Can only talk about my company, but we usually have strict naming conventions per project, and if you're gonna submit such code, they're just gonna tell you to fix it and read the conventions guidelines again.
Hmm fair enough, im sure i could manage then (meaning adapting to a companies naming convention) as long as im not forced to use snake case
Stuff is made from my nightmares, and 90% of the reason i hate godot
Well, snake case is a standard in some languages. If you're gonna have to write python you might need to use it.
You see i'plan to stay away from python i've been made to use it before and i really dont like it, it's designed to be too human readable and it just makes it harder for me to read
Same with lua, though not many things use this as far as i know
In Game dev, various tools are often written in python, so depending on what your company does, you might have to do it at some point.
And it's really not that bad. You can even delegate it to AI 99% of time and just confirm there are no issues.
You can even delegate it to AI 99% of time
Bruh
Though i guess that makes sense it's like the language ai was made in right?
Not really. It's just that most of the code shared online is python, so there's more training data for it.
But to be honest, this is kind of an overstatement.
More than that, simple tools usually don't have complex architecture and huge codebase, so it's harder for ai to mess up.
Fair fair, i do recall seeing awhile ago about someone who was using ai and it wiped a whole database on them cause they hadn't restricted its access
Honestly these "wiped the whole database" cases are probably 90% a human error. I bet they had things set up in a dangerous way or gave incorrect instructions and probably were not entirely aware how things work. I've been using agentic ai coding for more than an year now(both personally and at work), and I didn't have single case where a model would even get close to making such a critical mistake.
Usually it's more like messing up a powershell command syntax or forgetting to add a namespace using.
Which is extremely rare as of today as well.
what is a good workflow, making a centralized script that handles inventory slots, or make a script on the slot itself that handles dragging, splitting, and drag'n'drop?
Probably both. A script on the slot handling input events, and a manager script handling the logic of the whole inventory, listening to slot events, and such.
LazyLoadReference<T0> can i serialise this for json so my saved data correctly references a prefab or asset? or is it unreliable ?
never used it before so not entirely sure of its purpose
having a console error anyone able to understand this.
having trouble
I was midwhile following this tutorial https://www.youtube.com/watch?v=pcyiub1hz20
In this beginner-friendly Unity 2022 tutorial, I will teach you how to make your own amazing main menu in 15 minutes using Unity and C#
Like and Subscribe, it's free and helps the channel a lot!
If anyone knows ?
looks like you're trying to load a scene that hasn't been added to the scene list or build profile
This clearly doesn't have a scene 2 in it
your error says you're trying to load the scene at index 2
So how do i fix the error
you can see the scene indices right here
Either add a third scene to the build list or make your code stop trying to load it
Well it's pretty clear what the issue is from reading this code, no?
If you're in scene 1 and you run this code it will try to load scene 2
change the code to not do that
I apologize im brand new to unity/coding Im sorry.
You have nothing to apologize for
Do I remove the + 1?
No
Think about it
What should happen when you run Play and you're in scene 1 already?
you need to decide what should happen in that case
only when you come up with an answer to that question will you be able to write the code to do it
fahhh
It's not a trick question
Lowkey my mind is broken it kind of is for me
Do you want it to:
- Do nothing?
- Load scene 0 again?
- Load scene 1 again?
- something else?
It a loading screen so, I want it to change from the scene including the loading screen to the actual game scene
which scene is the loading scene and which is the actual game scene?
I only see "MainMenu" and "Game" in your scene list
Well your error is indicating that you are actually running this code when you're already in the game scene
so you need to figure out why that's happening and stop it from happening
that's your issue
is there any voice channel to live dev
no
If you want suggestions, post details in #1180170818983051344 This is a code channel.
Don't cross-post, please.
When I do transform.Translate(Vector3.forward) why am I doing these dots like WhT is their purpose
it shows you all the members and fields etc of that particular object/class
in the sceneario you demonstrated
I’m sorry I’m new is it possible to explain further
take a look at this docs: https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Transform.html
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#member-access-expression-
You access the members of whatever you're appending it to
guys i need help, for the OnTriggerEnter2D function, how do i specify which objects i want it to check for? For example: i have an enemy, when the player collides with the enemy the game ends, but right now if the enemy collides with something else (fx. another enemy) the game also ends. How do i specify so it's only on collision with the player?
it shows you the Transform class and all of the things that belong to it
Thanks
one common way is to use CompareTag. you simply check for the colliders tag that enters the collision/trigger
use layers to prevent collisions between enemies (or perhaps just for the trigger)
i see, so how would that look in code, like where would i use the CompareTag?
CompareTag gives a boolean, you'd check if the incoming collider has the right tag
There's an example on the docs for compare tag.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Component.CompareTag.html
Exactly what you're looking for.
but it's with magic strings, i'd recommend using layers for this. it fits very nicely with your usecase
you can configure some layers to not collide with certain other layers in project settings > physics/physics2d > layer collision matrix
oh yeah that works lol, thanks!
Yo i need help with something I can't find any tuts on it. I'm trying to make the animated 2d cloth like in hollow night or silk song when player triggers box it moves that way but its a bit buggy and just moves the wrong direction sometimes I'm. Using bools. how did silk song make theres
A user is getting a "Request timeout" error when a web request is being sent shortly after trying to send it, but my code is not setting the timeout field to any value.
Does anyone know what's going on here? According to the docs it doesn't seem like this should happen.
I'm not encountering this issue and neither is anyone else, it's just one person
Is this from a web request you create and send?
You probably want a timeout set anyway otherwise it can hang forever
It is - but do you know why it's timing out for them when I haven't set one?
It isn't hanging forever and is just timing out even though I haven't got one set.
It depends on the error/exception. I think this uses libcurl which may have extra functionality to cause a timeout still
Is there some kind of setting I can change to fix that?
The documentation seems to imply it won't timeout if none is set.
What do you mean by the actual error?
There's no exception being thrown, but result is ConnectionError and error is Request timeout
mb i usually await unity web requests which can then throw.
Im going to presume its some internal mechanism to timeout so may not be something you can solve
Best I can find is a 300 default timeout for a connection to be established
https://curl.se/libcurl/c/CURLOPT_CONNECTTIMEOUT.html
How can I master on scripting? I have fundamental knowledge on c#(for unity ofc) but I struggle with scripting. How would you perceive if you were in my state. I'm looking forward for some advice.
Tutorials and practice. There's no magic solution if that's what you're hoping for.
And add discipline to keep your scope small when starting out so you can achieve actual results.
Is this related to code? If not, try moving the post to #💻┃unity-talk
Make sure to provide more or as much information as possible to get better help from the community
I will do so. Just thinking how should i perceive that.
You just did?
-
If you plan on making something with the intention of making money off it, it's too big for you
-
If you plan on making something that the internet has convinced you is easy to make (ie, non-tutorial youtubers saying things like "I made GTA6 in 2 weeks"), it's too big for you.
-
If the idea would require more than one person to complete it's too big for you
-
If the idea includes any type of coop it's too big for you
-
If the idea is your dream project, it's too big for you
If the idea is boring, simple, and nobody around you will care to play it or find it impressive, then it's the right scope.
What i did and am doing is i made a project and started adding random features and slamming my hand against the keyboard until it works 🤣 for learning purposes and experience
Noted. I'm learning just for making an interesting game(not the studio level games).
Like i used to do with my coding agent telling him how it happened and fix that. It workd after several attempts eventually but left some bugs☠️
Just scripting or game development overall? This is a Unity game development server so we're more focused overall on the development of games. Relative to my own experiences, you'd be a good-enough of a scripter when you're able to implement your designs.
Assuming knowing c# and the Unity API isn't a concern anymore where you'd be able to quickly lookup what's needed when necessary and produce your wanted behavior.
tbh i would just start a txt doc of everything you would want your future games to have. then break it into segments . like for example "this week I'll learn the ins and out of the movement features I want" and then next week will be different
and don't expect it to come together into a finished product just learn and learn and learn
That's a good idea..
and make a folder where you can store a bunch of your .cs files so you have your mechanics and etc ready for your next project as a baseline
Yeah it never stops. If human don't have to forget everything they learn. However it could be worse in other way..
and i would take notes of previous issues you had while making certain things and what your fix was for it
for anything significant that is
like oh hey this one mistake created 70 errors lmao
a lot of the beginning phase of learning from my current experience is literally just lack of knowledge and experience
that's why i'm just focusing on the current project of slapping a bunch of random features i want to learn together
without any end goal game for the project
it might turn into something but if it doesn't then its whatever because it was a project for learning
It feels depressing when you don't understand a chunk of code that puts the logic even after trying to understand it.
join that so we don't flood this chat lmao
Vector3 MoveDirection = new Vector3(HorizontalInput * CurrentSpeed * Time.deltaTime, PlayerRB.linearVelocity.y, VerticalInput * CurrentSpeed * Time.deltaTime).normalized;
guys i was wondering if it was useless to add: * Time.deltaTime
no, it changes the values
it makes it incorrect in this case
oh wow thanks
you're normalizing this vector making it a direction - the y value shows it's a direction of speed
the x and z values have CurrentSpeed * Time.deltaTime, meaning they're positions (or rather, delta positions)
so you basically compare 2 values that don't represent the same thing here
if you (for example) added * Time.deltaTime to the second parameter, making the entire thing a deltaPosition, then it wouldn't matter since it's normalized (magnitude doesn't matter) and it's shared between all 3 components - you could remove all 3 in that case and get the same result
gizmos work kinda differently to Debug though
you could also make a helper method to draw a bunch of lines approximating a sphere, just to give you a rough idea of where it is
thanks
i'm so happy man
i can't believe i made my first 3rd person controller script
no AI
no tutorial
only help from people
thanks alot guys
glad you did it, tutorials are fine, ai for beginners not
yeah man, i will never use AI
is that even possible
well
i won't use chatgpt or stuff like that
i'm not talking about pathfinding ai lol
hehe okay
hell yah
i decided to add camera control which i think i should have done earlier, i used cinemachine but how can i make the movement depend on Head rotation too?
``` // GET WASD INPUT
float VerticalInput = Input.GetAxisRaw("Vertical");
float HorizontalInput = Input.GetAxisRaw("Horizontal");
// USE WASD INPUT TO MAKE A VECTOR3 THAT IS NORMALIZED AND MULTIPLIED BY THE CURRENT SPEED
Vector3 MoveDirection = new Vector3(HorizontalInput, 0f, VerticalInput).normalized * CurrentSpeed;
PlayerRB.linearVelocity = new Vector3 (MoveDirection.x, PlayerRB.linearVelocity.y, MoveDirection.z);```
use the transform.forward
thanks
is there a way to implement weapon sway with 2d sprite weapons and URP? i use a seperate overlay camera for the weapons
Curious as too how difficult it is to code character movement in a 2d game?
I’ve never done coding before
the answer, as with anything that open ended is 
You can make it either very complex or very simple, it depends
!learn 👇 get started with learning the engine, the pathways on the learn site are a good place to start with that. there's also beginner c# courses pinned in this channel
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
anythings possible
I'm having to deal with multiple unity version compatibility changes and the way I'm handling it is by using preprocessor directives to switch on detected versions. Will this work the way I expect it to? I feel dumb asking but I need some assurance. See screenshot. Youll see if I'm on a specific version where the API changed implementation then hit that code, now if its 2022.2 or anything in between that and 6000 will it hit that code? Then finally if neither are true and we're on pre-2022.2 itll hit some legacy implementation?
It will work just like if, else if, else so first block is for unity 6+ otherwise 2022.2+ otherwise older
Sounds good, thanks. I've only had to deal with preprocessor directives with enterprise code stuff so unity is a bit heavy handed with their use but I appreciate that they have these
yea they are just symbols that are defined for us to let us detect version easier
For some reason it says it's null when it's not?
amountMesh is null. Notice how the section for it in the log is empty
To see it better wrap it in quotations
it should't be null
It either can't find the object, or it doesn't have that component on it.
the debug.log shows "object", not n"null"
ok so i guess it is null... why is it null? I set it in OnStart
If you mean this, that's the function you are calling. Debug.Log with the object parameter. The log itself will show it being null easier if you wrap the object in quotations. Or Debug.Log($"'{amountMesh}' is null? {amountMesh==null} with amount {amount}");
It either can't find the object, or it doesn't have that component on it.
Log thetransform.Findby itself. If that is null, then the object doesn't exist.
And in any case, if this is just a label or similar, you can also just expose it to the inspector and assign it there to not have this problem :)
