#💻┃code-beginner
1 messages · Page 753 of 1
I think you can accomplish it with these parameters
float baseJumpImpulse = 20.0f;
float maxAddedJumpForce = 10.0f;
float timeToWaitBeforeAddingForce = 0.04f; // delay before adding jump - optional
The thing is, to prevent "press jump button, release, then press again and start adding force"
So you have to coordinate that, I'd think started performed canceled will be useful here
Is there an reason my class isn't appearing in the inspector
//Player DebugUI
[System.Serializable]
public class PlayerDebugUI : PlayerScript
{
public TextMeshPro PlayerVelocityText;
private void FixedUpdate()
{
}
}
That's not a MonoBehaviour you'll have to add an instance of it to a MonoBehaviour
PlayerScript
[SerializeField] myPlayerDebugUI PlayerDebugUI;
Ah i see.
will try it out right now
Check on the sprite sheet settings iteslef you are using Filter Mode = Point and wrap mode = repeat
SerializeField on a script object?
but that wont work
i assume
What doesn't work about it?
Also why is it a child of PlayerScript? 🤔
What is the goal with this overall?
I need to get the velocity variable in the debugui class
from the playerscript
and to do that making it the child saves me from requiring it
So... PlayerDebugUI is a MonoBehaviour too.
You can't rly get the variable that way - it needs access to the instance of PlayerScript component 
Whaat?! i thought you could
since it's a child
it would just recognize the parent variables
If you create an instance of it, in the PlayerScript, i suppose ...
There's much better ways to "share variables" that's all
You don't want to be inheriting that whole thing though.
Just add the require component, then GetComponent in Awake, and access the variable. 🤷♂️
Or keep that variable as a Scriptable Object and there are easy ways to access it from wherever.
Are you refering to static's?
i've tried them out. but my last project were really, i mean really unorginized in some areas
It's not needed, component instances can talk to each other easily
"Shared data" is a common topic in Unity ... easy to find on Google
That's an fair point.
i guess i should just really be reading other peoples conversations,.
Scriptable Objects are nearly identical to MonoBehaviour, except they live in a Folder in your project, rather than on a GameObject in the Scene
yeah this topic has been crossed before for sure
What?!
That sounds very important for larger and good orginizations
Besides my own experiences, I'm basically just telling you everything I've read online about it 🗿
can i write Methods in SO? and use them in other Scrpts? like APIS (is the Player Moving etc..)?
💀
and is this a good way because i write all apis in my Player Movement Script
like SlowForTime.
ScriptableObjects are like MonoBehaviours except they exist outside of a Scene. They live in your project, like data, rather than a behaviour, which is in the scene. ScriptableObjects don't get events like Update().
i've modded some games before, and their scripts are orginized in folders, i need to learn scriptables at once
is this a answer to me?
so? i can write Methods for the Player? i assume
It's not valuable, but it's possible
so its just better if i use it on the normal Scripts?
MonoBehaviour gets all the callbacks. ScriptableObject is mostly for storing data that can be easily accessed project-wide.
Or for configuration - they hold their values when Playmode ends, unlike Serialized fields.
For example you'd rather have a ScriptableObject for tuning your character. Movespeed, rotation speed, jump height, strength of gravity, etc
When you have a configuration you like, you can just duplicate that ScriptableObject asset file, and then it's there whenever you wanna switch back.
@tender mirage @scarlet pasture simple example
[CreateAssetMenu(fileName = "PlayerRuntimeStats", menuName = "Scriptable Objects/PlayerRuntimeStats")]
public class PlayerRuntimeStats : ScriptableObject
{
[HideInInspector] public Vector3 position;
[HideInInspector] public Vector3 velocity;
}
Now in your MonoBehaviour, you can just reference an instance of these stats (created before runtime, either find by name or drag & drop by serializing), or create one at runtime and put it in a location you will access from other scripts.
Unity keeps track of whatever folder you name "Resources" so that can be a fine place for that kind of thing.
But it's easier to just create the object beforehand - unless you have multiple players (co-op) or something like that.
😂
✅ Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=7jxS8HIny3Q
Let's learn all about Scriptable Objects and how they help us make our Games Designer Friendly!
👇
🌍 Get Code Monkey on Steam!
👍 Interactive Tutorials, Complete Games and More!
✅ https://store.steampowered.com/app/1294220/
Make your Games De...
i was just watching the tutorial
it looks incredibly useful
i gotta admit
Avoid CodeMonkey, he writes really careless & wrong code
Applying lerp so that it produces smooth, imperfect movement towards a target value.
I generally avoid tutorials
don't worry about that.
although.. i do get stuck sometimes on silly things.
i dont really watch totrials, i had the feeling that i even code the basicst stuff.
even cant*Ü
yeah, although tutorials aren't even the worst nightmare anymore
traps like ai are most more harmful and there are geniunally people that fall for it.
Definetly
this is way i ask here ervthing like last time i didnt even know how to set up a Vector to the Player and asked here
and also reading docs
i try to learn the Code by doing it reather than asking Ai, i think this can help me to understand the Code better
Hell yeah man. now that's the power 💪
Y'know the feeling of just solving problems. it's great
And yeah, you get much better muscle memory
by trial and error
rather then asking some statistical machine to generate answers
can someone help me with AI Navigation, i have tried basically everything and i cant find out how to make my AI stop hugging walls
see #🌱┃start-here for what to include when asking for help
ok ig
So uhm my AI hugs walls in hallways. Heres my script: https://paste.mod.gg/rrzcqrbpywcq/0 I’m using a NavMeshSurface and NavMeshAgent, step based movement, agent radius 0.65, and hallways ~5 units wide. Tried center offsets but it still touches walls.
A tool for sharing your source code with the world!
why do u use print?
does that work in unity?
yea
wow
is that better?
its the same
its faster for typing haha
just faster to write and better to memorize for me
yea well it works the same as Debug.Log
i wish i can help u but im to bad hah
one time i just wrote print as a joke and then tested it and it worked
hahaha
on this day im also starting using print haha
yea well my Only issue is AI Navigation stuff bc this AI keeps kissing walls and wont stop
but can u say Debug.LogError
i didnt even know that existed tbh
maybe u need to change the Settings on the Nav Mash component, and Bake the Scene Again
i only used one time so i dont know really
i already tried everything possible
without seeing the setup it will be difficult for anyone to help
does someone know what could cause these hard edges between my chunks? the y levels are generated using the same noise algorithm and should be equal
Hey everyone im trying to make a mouse over object detection script but when i hover the mouse over the instance of the object it gives me "Object reference not set to an instance of an object" error anyway to solve this error?
I also wanted to say that the script works normally on the original object and only gives this error with the instances of the object
show code + setup
Ok
you need to expand the Console window and show which line # is the Null Reference Exception
also don't send video/screenshot of code. Use pastebin links 👇
!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.
Idk how to use pastebin
click one of the links I sent, paste code there, save and send link generated
Ok sure
A tool for sharing your source code with the world!
Like this?
yea
I also used ai for the code sooo
probably shuldnt have said that
Idc
now no ones gonna wanna help you..
if u didn't write ur own code and don't understand what the chatbot gave u.. what makes us think you'll understand the solutions for it 🤔
I can tell by the unicode chars in the comments..
At least he is honest
it's against server rules to not disclose that, so it's better that they actually admit it instead of trying to be cheeky about it
Idk man im trying to fix my problem
at the very least you have to understand what the code is doing and what the lines means, otherwise any suggestions to a fix will be moot
^ this is basically what i was sayin
I understand some of the code
Ima take a wild guess its probably selected throwing NRE but without seeing the line its a guess
☝️ same
for all we know it could also be Camera.main or another script :\
You ppl can understand what im trying to make from the code right?
selectedObj is a cheeky script name 😅
drag and drop?
Im a beginner with 1 week of expirience what do you expect dude😂
Yeo
what do you mean by "you people".. 🤣 yea we sorta guess
onMouseEnter u set selectedObject's selectedObject variable to 0
onMouseExit sets it to 1
My english aint good😭
!learn If I were you I’d use unity learn to learn c# it’s a really good resource and you can learn how to make code and debug issues like these
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
SelectedObject is used so an object doesnt spawn inside another object
its rather confusing b/c selected.selectedObject = 0;
is basically the same as selectedObj.selectedObject which is confusing just a bit
Yep i know
the naming would help a lot.. but u get better at naming as u go..
u said ur just 1 week in.. soo i wont hold it against ya lol
I used scriptable objects for global values
or just check the inspector
It is asigned
also you outta check the lines number on the nre
ya, something is not assigned which is what null is
I shoud just rewrite the script😓
for all we know its an entirely different script..
"use this reference".ToDoThisThing();
but the ide is like "that reference isn't referenced"
it might help.. take it (1) function at a time
don't continue until u get the basics working
Ok sure
once it works its repeatable..
if u do it all at once and it doesnt work.. its much harder to figure out where it went wrong
especially when learning
should take small bite sized pieces
are these spawned at some point ?
Sure i wanna learn anything myself without courses yes it takes longer but i learn more things
looks like the SO is only assigned to the Instance in the scene and not the original prefab
Yep when you left click
then its probably not assigned in the original prefab
as indiecated by the "bold" text and blue line next to the name
Hands-on learning / Trial and Error is always the best way to retain information
How do i assign it?
go into the original prefab and assign it
Yes thats right
Assign the script?
the scriptable object..
the only thing that I said was clearly only assigned to the Instance in the scene.
if (selected == null)
{
Debug.LogWarning($"selected is NULL on {gameObject.name}", this);
return;
}``` ^ you can actual put null checks *in* the code
that way if its not assigned theres no errors...
and you can still have debugs to log it to urself..
I have a question what does "return" do?
it returns out of the function
{
if (target == null)
{
Debug.LogWarning("No target assigned!", this);
return; // exits Update() early
}
// If we got here, target exists — safe to run logic
transform.LookAt(target);
Debug.Log($"Tracking {target.name}");
}```
^ chek the comments on that it'll make more sense
Thx
Generated codes are like free money falling from the sky. Since you get free money, you won’t work to gain experience.
This message is copyrighted by Rod. All rights reserved.
if thing isn't there -> dont do anything else
sorry i was just bored
if thing is there -> go for it
Cool
I will keep that in mind
Early return if u wanna research it urself
is what its called in this context
Hey, how can i add a force to my player with a Strong value but only for a few Meters?
i only know how to apply force but i dont know how to make it that he only goes a few meters
store the position when u start the force.. (check distance until its too great) then stop
how can i check the distance?
Vector3 start = transform.position;
body.AddForce(dir.normalized * impulseForce, ForceMode.VelocityChange);
while (Vector3.Distance(start, transform.position) < distance)
yield return null;
body.velocity = Vector3.zero;```
yes exactly ^
THANK U SO MUCH!!
once the distance check fails u set it back
that will need to be run in a coroutine in case u hadn't used those before
if i use that in a antoher Script i need a Corutine? and a while loop? right because i need to run this code more then one time?
like cs public void FireImpulse(Vector3 dir, float meters) { StartCoroutine(ImpulseDistance(dir, meters)); }
using System.Collections;
private IEnumerator ImpulseDistance(Vector3 dir, float distance)
{
Vector3 start = transform.position;
body.AddForce(dir.normalized * impulseForce, ForceMode.VelocityChange);
while (Vector3.Distance(start, transform.position) < distance)
yield return null;
body.velocity = Vector3.zero;
}```
for using yield (thats what makes it wait) it'll have to be in a coroutine
I FOUND THE PROBLEM
brother.. I been telling you the problem
no shot 👀
ops the red should be circled above
can i say if scale is -1 he is looking left? and give the player a force to left?
I told you to not pay attention to that script
lol.. 🫰 darn
Im not talking about that
i been said its the prefab without the assigned SO
Blue line = its not the same value as the original prefab
an easier way is to just negate the force... easy enough..
you're spawning new prefabs with SO not assigned
positive 100 -> moving to the right
negative 100 <- moving to the left
or up/down or w/e
How do i assign selected to the instances?
I told you lol..You literally have to open the original prefab and assign it there
no need to really check the direction unless ur wanting to do something like change the graphics to correspond to the direction ur moving
then u can just use inputs...
Ok ok let me try it
if input = D -> moving right (graphics facing right) + forceToApply
if input = A <- moving left (graphics facing left) - forceToApply
Nav's the best 🤜 🤛
now go tell ur AI bot how stupid it was.. and tell it to never ever screw you over like that again 😉
Mess with the Best, Die like the Rest .
little 90s nostalgia for ya
I am not going to use ai for the rest of my learning just for explaination
thtas a good thing to do 👍
u can use it as a study helper... giving u things to go and look up on ur own..
it isn't too bad at refactoring code either.. (once u write some nasty code urself)
u can have it help tidy it up.. (for the most part its decent at that)
now the boxes wont spawn inside each other🥲 🥲 🥲
Next bite sized bite
welcome to dev. Going from one problem to the next
half the time bugs be hiding behind other bugs 😅
programming, the act of putting bugs 
Alright imma go to sleep i need to go to school tomorrow so byee👋 👋
hangon
Impulse is a one-time all at once force..
it wouldn't make sense to use it over distance..
unless you want a instant DASH that dampens to zero over time or something
which is a bit different
{
if (transform.localScale.x > 0f) //Rechts
{
isFacingLeft = false;
}
else //Lin,s
{
isFacingLeft = true;
}
StartCoroutine(ImpulseDistance(dir, meters));
}
private System.Collections.IEnumerator ImpulseDistance(Vector2 dir, float distance)
{
Vector3 start = transform.position;
rb.AddForce(dir.normalized * impulseForce, ForceMode.VelocityChange);
while (Vector3.Distance(start, transform.position) < distance)
yield return null;
rb.linearVelocity = Vector3.zero;
}```i did it like that
i need to chanfge it to Vector2 haah
simple enough.. do that and see if its what ur going after..
no i mean its simple enough to change to a vector2
ForceMode is for 3d, perhaps there's another (similarly named) type you want to be using there instead? consider reading the documentation for that method to find out
okay i will try it
rb.AddForce(dir.normalized * impulseForce, ForceMode2D.Impulse);
but know i cant use => velocityChange? i saw that its the same like Impulse but just ignore the mass, can i just set the mass to zero and after the Attack back again to the saved value?
in 2d only Impulse and Explosion exist, i think impulse should be fine. i just add a high value and the distace check should set the player to zero
hmmm i also saw that i cant use Coroutine for Animation Event
i need to use it in the Code spezifical altought i didnt like that
Any idea when i play the sound, it take a bit of time before the sound is being Played.
in the AudioSource, there is a clip, a .wav with Decompress on Load, PCM,
using PurrNet;
using UnityEngine;
...
[RequireComponent(typeof(SoundPlayer))]
public class ObjectInteractiveRat : NetworkBehaviour
{
...
[ServerRpc]
public void Activate()
{
if (isActivated) return;
if (type != InteractionType.DepositSpot)
isActivated.value = true;
GetComponent<SoundPlayer>()?.PlaySound();
ActivateInteraction(type);
}
using UnityEngine;
using PurrNet;
[RequireComponent(typeof(AudioSource))]
public class SoundPlayer : NetworkBehaviour
{
[ObserversRpc]
public void PlaySound()
{
PlayLocalSound();
}
private void PlayLocalSound()
{
AudioSource audioSource = GetComponent<AudioSource>();
if (audioSource.clip != null)
{
audioSource.pitch = Random.Range(0.97f, 1.03f);
audioSource.PlayOneShot(audioSource.clip);
}
}
}```
multiple ways you can go about it but I like controlling my Vectors completely myself and just setting the rigidbody's vel
- check for input / start coroutine
// Dash input
if (Input.GetKeyDown(KeyCode.LeftShift) && !isDashing)
{
Vector3 dashDir = new Vector3(rb.linearVelocity.x, 0, rb.linearVelocity.z).normalized;
if (dashDir.sqrMagnitude > 0.01f)
StartCoroutine(DashRoutine(dashDir, dashDistance));
}```
- dashVelocity is its own Vector I can control completely.. so if there is a value it gets added into my over-all vector.. if i **zero** it out.. it doesn't affect my original vector
```cs
vel += dashVelocity; // add dash velocity
rb.linearVelocity = vel;```
- the coroutine's job is to cut it off or zero it out once a condition is true, either by distance, or by time, or w/e you chose
```cs
private IEnumerator DashRoutine(Vector3 dir, float distance)
{
isDashing = true; // start dash
Vector3 startPos = transform.position;
dashVelocity = dir * dashForce;
while (Vector3.Distance(startPos, transform.position) < distance)
yield return new WaitForFixedUpdate();
dashVelocity = Vector3.zero; // stop dash
isDashing = false; // allow next dash
}```
Hello gays what Code c++
thats c plus plus unity uses c sharp
Code c++ is :C plus plus and is what engines like Unreal use to code with..
Code c# is: C sharp and is what Unity uses to code with..
Pon
say I have a persistent scene that holds my game's main camera + post-processing setup.
each game/level scene (Level1, Level2, etc.) needs its own post-processing volume with different looks.
I’ve been debating how to handle this most of the morning:
A) Keep one persistent volume and find/apply the correct scene’s volume profile on load.
B) Let each scene use its own volume component (engine handles it).
C) Have a central manager with a list of scene names + profiles and just swap on load.
which setup do you guys prefer?
(im also curious b/c this idea can apply to multiple things and would change the way i build from here on)
Thank u so much, cant belive that u really gived such a detailed explanation
@rocky canyon are u are inid Dev=
it just so happens to be a chunk of a prototype controller im working on
That topic is not allowed here
are u guys talking about me?
yeah you arent allowed to thank people here
jk someone was talking about modding
wasnt you i think
Video game modding (from "modifying") is the process of player and fan-authored alteration of a video game and is a sub-discipline of general modding. A set of modifications, called a mod, can either alter an existing game or add user-generated content. Modders, people who mod video games, can introduce a variety of changes to games, including a...
they are referring to the person who deleted their post
ah okay now i understand
i will try making a small platformer project having one level and come back once i complete it.
if u want we can work togehter?
i don't really know anything there is to know, i am absolutely new to this. I made 4 games before this using pygame but this is my first time touching unity.
I don't really know whether I would be of much help honestly
mostly a 3d-modeller/ui-ux stuff.. (i only make games as a hobby/fun)
np im abolutly trash
we both can learn from each other
when did ya start out?
a long time ago, but i didnt realy do somthing
totall maybe 2 months
i guess that works...?
active time
mine's 0 xD
i hope so
no problem, i think togehter we can learn alot
will friend you for the time being. gonna ping once i complete atleast one game
so wholesome
!test-requests
Asking for testers via DM is a suspicious activity. Please upload your game to a publishing platform and make a #1180170818983051344 post. Use Itch.io or Unity Play if you are unfamiliar.
⚠️ Users should use the utmost care when dealing with executables, compressed archives, or .apk files. A common scam involves fake games that seek login tokens or other private data, compromising accounts, and potentially bypassing two-factor authentication.
CustomPropertyDrawer fails to call OnGUI in some cases
Is there a downside performance wise to using a GameObject [MonoBehaviour] based State Machine for relatively simple entities?
I ask this because the convenience of being able to use SetActive() to disable and enable GameObjects for such a state machine + the visual organization would be quite handy.
just try it
perf should be fine
Its not like I'm going to have thousands of entities on the screen A and B: I do plan to disable entities entirely when they are off screen, and enable them when they are off screen anyways....
Cool, thanks!
am not enabling and disabling them have custom editor logic to visualize but have state hierarchal state machines represented with game objects and some of hundreds of states and its running fine
it can be nice since it makes visualzing them easy, but also means your states can easily make scene references
how do i restore broken prefabs?
(before anything, i do have a github for backup, but i want to know if there is other options)
i was changing a flamethrower particle/light in my enemy prefab, then my whole pc goes brrrrrrr (frozen screen)... it shuted down and when i open unity again a lot of things on the scene (which as prefabs) had been corrupted.
how's the stardard way to solve it?
File corruption is not really something you can recover from. It could be just a missing character or the whole file being empty, or encoded in a weird way, and you wouldn't have a way to restore it without knowing what exactly is wrong with it. That's what version control and backups are for.
Different people/projects do things differently. Note some projects use shared textures for multiple models making the latter infeasible
Also not a code question
this is the wrong channel, rip
anyone got any idea how you do floating origin rebasing on a multiplayer game?
each client has their own floating origin
but really it's complex, especially if there's physics involved
the server might have to run a physics sim for each "bubble" so to speak
its already a fiddly soultion to a problem, but turns into a fiddly and very complex problem if he floating origins need to be networked as well
That's why you don't really see many games with such features built on Unity. This is something you'd probably want a custom engine for.
Not just this, but in general, a game of such scale and complexity.
also lot of game that need it work around it in other ways
like large universe for the player but PVP kinda happens in its own zones
you dont need a custom engine for this unigine and unreal both solve these problems with 64 bit maths hopefully unity joins the party soon. 🙁
I guess the real solution here is to use ECS on the server side and implement my own shit using double
What I'm saying is that a complex game like that might require a lot more tailoring to its needs, so a custom engine is often the preferred choice.
It's not just the floating point issue. There are a lot more considerations.
honestly if I had the time/skill I probably would have my a custom engine for this game
yes I know that but floating point is the one I haven't found a solution to since its multiplayer
Point is big games require a lot of consideration, resources and human hours. Something that usually big companies have, not individuals. They can afford to develop an in-house engine for the task.
So is what you''re suggesting its not possible in unity?
No, definitely possible. But it might be more difficult or problematic in the long run(compared to an engine designed specifically foe the task).
And you mentioning ECS is a good point. It might make such problems easier to solve.
All I'm saying is "don't bite more than you can chew". (or I guess do it at your own risk)
im cutting tons of corners elsewhere to make it feasible for me to finish this lol. the server isn't simulating any logic to be a source of truth and its just doing some sanity checks on what the clients are doing which is saving me tons of time.
It would involve chunking the universe properly, and then simulating each chunk separately that has players in it (well, only the server would need to simulate all chunks every tick).
This is assuming you're doing a server authoritative prediction/rollback thing.
Star Citizen does 64-bit floats so they don't have to do this... but their game also runs like a hunk of garbage, even with their endless millions of dollars in funding
Chunk borders (literal edge cases) would get weird if you've got players fighting on it, or physics happening across it. I used to be pretty interested in solving this problem until I realized how much work it would be.
I dont think real origin shifting (different from the chunking I described above) would work for multiplayer with proper rollback, because the server's origin would be different from the client's origin and you're probably going to run into strange determinism issues. Or maybe not. I dont know.
You said the server doesn't need to simulate anything, so that probably makes things 100x easier. You certainly don't need 64-bit floats or a custom game engine to do this.
Load the entire model at once just like Nintendo 
debunked btw
Is there an reason why multiple class child class isn't working at all?
public class PlayerScript : MonoBehaviour
{
//Player movement class
[System.Serializable]
public class PlayerMovement : PlayerScript
{
//Components
private Rigidbody2D playerRigid;
//Player Properties
[SerializeField] private bool IsMoving;
[SerializeField] private float playerSpeedX = 0;
[SerializeField] private float playerMaxSpeedX = 3.5f;
private float playerVelocityX = 0;
private void Awake()
{
//Get Components
playerRigid = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
InputMovement();
}
private void InputMovement()
{
//Right left movement
if (Keyboard.current.dKey.isPressed)
{
//Apply speed
playerRigid.linearVelocityX = playerSpeedX;
//Build speed
playerSpeedX = Mathf.SmoothDamp(playerRigid.linearVelocityX, playerMaxSpeedX, ref playerVelocityX, 0.6f);
}
else if (Keyboard.current.aKey.isPressed)
{
//Apply speed
playerRigid.linearVelocityX = playerSpeedX;
//Build speed
playerSpeedX = Mathf.SmoothDamp(playerRigid.linearVelocityX, -playerMaxSpeedX, ref playerVelocityX, 0.6f);
}
else
{
playerSpeedX = Mathf.SmoothDamp(playerRigid.linearVelocityX, 0, ref playerVelocityX, 1);
}
//Up down movement
if (Keyboard.current.wKey.isPressed)
{
playerRigid.AddForce(new Vector2(0, 15));
}
else if (Keyboard.current.sKey.isPressed)
{
playerRigid.AddForce(new Vector2(0, -8));
}
}
}
}
my player doesn't move anymore
after applying the sub class
Does fixed update not work inside of a subclass perhaps?
you need to add the PlayerMovement script to the GameObject, not the PlayerScript
So, i would need to create multiple scripts to have multiple classes?
that said, this is a very strange way of organizing the classes, I would recommend against it
I’m pretty sure every monbehaviour definition needs its own monoscript file but i could be mistaken
Yeah, i've never touched on multiple classes before, but i wanna solve the problem of my code always turning out unorginized
can't i just have multiple classes in one larger script? that's how i would like to orginize my projects.
so PlayerScript > PlayerMovement, Stats, etc
it's unlikely that you will solve any organization issues with nested classes
you can have namespaces though
That’s not how almost any project is done, no
which channel should I post on for unity related beginner problems?
Then, should i just go back to using 1 class
the class split is not bad, this is a good approach using composition
you just need to move them to different files
try researching a bit about OOP and composition, then you will most likely be able to organize the project better
Yeah, Will do.
I would love to have multiple classes in 1 script to be fair
But fair, in the inspector, i suppose seperating scripts and their components to configure them
would be alot cleaner
Unity just does not support this for monobehaviours so dont
Used to mess around with javascripts. and the scripts i worked on were one large script with multiple classes
suck it up and stop
Im sorry to hear that
large files are usually a pain to work with, this is a better approach
Your safe now
Its a bad idea in general because your source control management will take a shit
lmao
Well, i certainly wasn't expecting this.
Still, thanks for the advice
peep
welcome to the real world ✨
Sure.
Imagine my toilet and shower instruction manual being printed in the same booklet because their both bathroom related
so tempted to correct you there
To build it not use it!!
Yeah, no clue why the scripts i was messing around with were structured like that...
and then i ended up structuring my scripts like that myself, especially on lua, it got much worse.
thank god i was atleast using modules here and there but still..
to be fair, languages like JS and lua let you do crazy things
but in strictly typed languages its a different story
You can put as many classes into a single file as you want. But it can be considered bad practice
Yeah, i can see why now.
also multiple scripts in the inspector seems like a better approach anyways
a component/class should try to do one job
rather then 1 large script component
Yeah, i honestly can't believe i've not been doing that
as you do more you learn what not to do
e.g. make one mega script and realise later you really need to re use something elsewhere
managers scripts type shi
Yeah.
Hey
Can Sombody help me, i try to fix it since 1 hour, my Player Cant flip. I Event coded it and somthing isint working right. I Really dont know what: ``` public System.Collections.IEnumerator ANIM_LightAttack()
{
if (isDashing) yield break;
if (isCurrentlyAttacking) yield break;
if (playerMovement2DScriptRef == null) yield break;
isCurrentlyAttacking = true;
playerMovement2DScriptRef.allowFlip = false;
playerMovement2DScriptRef.allowDash = false;
anim.SetTrigger(LightAttack);
anim.SetBool(WalkParam, false);
yield return new WaitUntil(() => anim.GetCurrentAnimatorStateInfo(0).shortNameHash == LightAttackState);
yield return new WaitWhile(() => anim.GetCurrentAnimatorStateInfo(0).shortNameHash == LightAttackState);
isCurrentlyAttacking = false;
if (isCurrentlyAttacking == false)
{
playerMovement2DScriptRef.allowDash = true;
playerMovement2DScriptRef.allowFlip = true;
Debug.Log("ich darf" + playerMovement2DScriptRef.allowFlip + "");
}
}```
what do you mean by "can't flip"?
like i coded in my Player Script a Flip functionen with a bool. When bool is true he can look to left or right
in every other Animation it work but not in the Attack Animation
when i say allowFlip = false, rthe player dont react to the Inputs of the Player and he cant look to the right or left
the issue is after the Attack he should flip and look in both direction inpendet with the Inputs. but he is just frozze im his current loock diraction
he only can look to right as a example. even i cleraly said he is allow to look in both diractikon.
also the debug isint really fired. i dont fint the issue tbh
then that's a clear issue - that code isn't being reached
yeah i know, but i dont understand why
add logs further up - before the waitwhile, etc
did, it runn until it reach this line =>
yield return new WaitWhile(() => anim.GetCurrentAnimatorStateInfo(0).shortNameHash == LightAttackState);
when im making an animation in blender and export it in unity why is it in so many layers
altought the Animation ending, so it cant be the issue. i thought abut just set allowFlip = false in my Combat System.
{
state = AState.Startup; elapsed = 0f;
lightHitbox.enabled = false;
Vector2 dir = transform.localScale.x > 0 ? Vector2.right : Vector2.left;
if (anim != null) StartCoroutine(anim.ANIM_LightAttack());
}
void EnterActive()
{
state = AState.Active; elapsed = 0f;
if (lightHitbox) lightHitbox.enabled = true;
Debug.Log("Ich sollte angreifen!");
Vector2 dir = transform.localScale.x > 0 ? Vector2.right : Vector2.left;
FireImpulse(dir, lightLungeDistance, false);
}
void EnterRecovery()
{
state = AState.Recovery; elapsed = 0f;
if (lightHitbox) lightHitbox.enabled = false;
}
void EnterCooldown()
{
state = AState.Cooldown; elapsed = 0f;
}
void EnterIdle()
{
state = AState.Idle; elapsed = 0f;
inputBuffered = false;
if (lightHitbox) lightHitbox.enabled = false;
}```
i think i would be better in herer
so Chris do u know what the issue can be?
if the debugs point to that being the issue, then that's likely the issue
yeah...
i heard in the internet with Somthing about "try" and "finnaly"
never used that. i give it a try
that's not relevant
log some more values then
okay!
specifically, the things you;re checking
i mean? is the Animation playing?, is the Animation ended?
i think this can help
also check if you're looking at the right animator
yeah, in the Console is "invalid Animation Layer"
but i fixed it
i just put the allowFlip logic in Combat System. I think its either way better to handle that in Combat System instead of in Animation Handler
but i hope the Code block dont give me more problems in future haahah
haha i did that in my Combat System but i also know why it didnt worked befor. i had the wrong Name in the Animator Graph. i called "LightAttack" but in my Code i just Checkt "Light"
Have a simple shooting script where the sphere will fire a cube from in front of it. For some reason, even though the sphere / firing point is rotated, the cube never changes on the y axis. The EXACT same script on my player can instaniate the same cube going wherever he's looking. Any ideas? Both scripts just use: Instantiate(fireball, transform.position, transform.rotation);
youd need to post 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.
please post it properly as the "large code blocks" section instructs
A tool for sharing your source code with the world!
I made it so when you hold the space bar you jump higher and when you tap it your suppose to jump less high that the normal jump height. But instead this happens (watch the video). Any ideas on how to fix this?
Well first of all from the looks of it nothing resets jumpPower
So each jump will just grow larger than the last even if it was a "tap" vs a "hold"
AHHH yes your right, I forgot to do that lol thanks!
It works now thanks for that
How would I make it so when I tap the space bar once it goes to a specific value same with holding cause right now if I just tap it the player barely jumps and its building up the value which I dont want.
My first game I did something similar to you with using impulse for the jumps if I was to go back I would never use a forceMode of impulse but instead just set the rigidBody.velocity.
this is what my code ended up looking like to get the jump impulse to cancel itself in my case though I'm setting a constant speed not adding to it each time: if (cutJump && !(jetPackPowerUp.activeInHierarchy || permaJetPowerUp.activeInHierarchy))
{
rb.AddForce(computeJumpVector(true) / 2, ForceMode2D.Impulse);
cutJump = false;
}
Tapping and holding is a bit hard to separate. I would rather track when the button is held down to apply the jump force, and then wait for the button release to apply a little downward force so it stops jumping higher. Either with AddForce or setting velocity. That’s my idea
How would I add RB.velocity I've never used it before, how would I add it to my current code?
So, I have an extremely annoying problem that I've been trying to tackle for hours without success. The issue is: I'm trying to move a dynamic rigidbody 2d with linearVelocity. I can see that the velocity is changing if I Debug.Log it. However, the object remains perfectly still. I would guess that it's doing so because the animator that I'm using is setting its position and doesn't allow to change it via code, as if I disable the animator, the object DOES move. However, setting the transform directly or using MoveTowards still works for some reason. I think the reason is because in another, unrelated clip, I do set the position via the animation tab. How can I solve this? I've tried enabling and disabling the apply root motion but still nothing
just do rb.velocity = new Vector3(0, jumpForce, 0). then when you let go of space you can do rb.velcotiy = Vector3.zero in order to cancel any upward force.
ok wtf update: I've tried removing the position property from that one clip and on every animation it's still showing that I'm animating the transform. What is even happening
Why are u setting the position with animation and code at the same time?
are you doing anything with the scale / rotation? I had a similar WTF where I had an animator also doing things with those properties that was also messing with me.
yeah that is a good question, that's why I thought "ok no let's just remove this position property from the animation and I'll do it via code", I did it and it still doesn't work ,it's still showing as if I'm animating the transform even though I'm clearly not
So shall I keep the code the same just swap this part out? →
rb.AddForce(new(0, jumpPower * jumpMultiplier, 0), ForceMode.Impulse);
I think you can also get rid of the jumpPower += Time.DeltaTime; if you set the velocity and instead just make jumpPower a constant but it's hard for me to know exactly without seeing where HandleJump() is being called.
its being called in Update
ok I removed the property and put apply root motion to false and now it works. I'll just leave before I insult this god forsaken engine so much that I get banned from the server
If u set the transform directly by any mean, it will override the physics-based movement. I’m not sure about the animator thou
probably best to leave that as is then. and just set the rb.velocity. Also I think you might want to move it to FixedUpdate() later on as setting forces in Update() can sometimes cause random issues with physics.
You are calling AddForce in Update?
I was before but I'm using velocity instead.
Update and FixedUpdate are not in sync. Typically the way to accomplish this is to receive the input in Update, store it in a variable, and "consume" it in the next FixedUpdate.
Like this? also its still building up the value which I don't want
No... Something like this
what is u goal?
u only want to jump one time? or consitentyl?
No, when I tap the space bar I want to jump just a little high but when I hold the space bar I want to jump the normal height / high
ahhhh
how long do u code?
first u need to check is the player currently pressing the button and not in the air
Technically the longer u hold the key, the higher u jump
@red igloo
// Verbose example for extra learning & clarity.
bool jumpHeld = false;
public void jumpButtonPressed(InputAction.CallbackContext context)
{
if (context.started)
jumpHeld = true;
if (context.canceled)
jumpHeld = false;
}
void Update()
{
}
void AddInitialJumpImpulse()
{
rigidbody.AddForce(..., ForceMode.Impulse);
}
void AddAdditionalJump()
{
rigidbody.AddForce(..., ForceMode.Force);
}
float maxJumpCanBeAdded = 10.0f;
float currentlyAdded = 0.0f;
void FixedUpdate()
{
if (jumpHeld && !characterIsJumping && jumpAvailable)
{
AddInitialJumpImpulse();
currentlyAdded = 0.0f;
}
else if (jumpHeld && characterIsJumping && currentlyAdded < maxJumpCanBeAdded)
{
currentlyAdded += Time.deltaTime; // in FixedUpdate this is automatically fixedDeltaTime.
AddAdditionalJump();
}
}
coocked fr
@red igloo let me know if that makes sense.
Note that This doesn't prevent "press jump button, let go, then press again and still add more force"
- you can handle that easily with an Enum I think.
Also I highly recommend trying ForceMode.VelocityChange (will require different scaling of force applied)
they aren't working in 2d
yeah they dont work
what did u said? i dont understand u my bad
so they are using ForceMode, which has 4 modes
yeah i saw it my bad
the 3d and 2d engines are actually different third-party engines, so they work differently, they provide different things, there are subtle inconsistencies between them, such as this
ForceMode (3d) has 4 modes - Force, Impulse, Acceleration, and VelocityChange
ForceMode2D has only 2, Force and Impulse
the explosion force you're thinking of is not a forcemode, it's a separate method altogether that exists in the 3d version
didnt know that thank u
i... don't know how it's different from an impulse/velocitychange force though. i work in 2d
(Also that method takes forcemodes itself as a parameter)
AddExplosionForce is basically just a convenience method for adding a force outwards from a central point with a distance falloff (direct inverse linear relationship) and an optional extra "upwards" modifier
oh... i've reinvented that...
I have never used context started / callbackcontext. do you need the player input component? if so I don't use that I use input action references
you do not need playerinput, no
you can use playerinput with these, but as the name suggests, this is just for a callback on the event
Chis can u pls tell me how to post a huge code, i need help and the code is really big for dc
thank u
!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.
please don't ping random people you aren't currently talking with
sorry
Hey everyone, i have a dumb question:
When we reference the rigidbody in unity like
Public RigidBody2d rb;
Why do we have to get the component in void update()?
Didnt we already reference the component in the script?
you don't have to "get the component" if you already have it referenced
Note that:
public RigidBody2d rb; simply creates the variable
the actual part where you set up the reference needs to be done in the Unity editor in the inspector
if you didn't do that, then you just have a null variable, not a valid reference
its so you can click and drag in any object matching the type not just ones on the current GameObject
Why do we have to get the component in void update()?
Do not
Don't do get component in update basically ever
You get it in start because of all the things Praetor said
Those people are wrong
Update runs every frame. GetComponent is slow. There is zero point in re-getting the same reference every frame
Do it in Start or Awake
Oooh ok
you'd really have to show the particular individual circumstances you're talking about. Different situations call for different things.
There are also inefficient and wasteful ways to do things which people absolutely do, usually from a lack of understanding
This is why u double check everything
I always get a null reference whenever i try to grab the script from a another object and output a text variable
TMPro;
using UnityEngine;
using UnityEngine.UI;
public class PlayerDebug : MonoBehaviour
{
//Components
[SerializeField] private GameObject playerVelocityObject;
private TextMeshPro playerVelocityText;
//Scripts
[SerializeField] private PlayerMovement playerMovement;
private void Awake()
{
//Get Components
playerVelocityText = playerVelocityObject.GetComponent<TextMeshPro>();
}
private void Start()
{
UpdateText();
}
private void UpdateText()
{
playerVelocityText.text = "VelocityX: " + playerMovement.playerRigid.linearVelocityX + "\n" +
"VelocityY: " + playerMovement.playerRigid.linearVelocityY;
}
}
using NUnit.Framework;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.InputSystem;
using TMPro;
public class PlayerMovement : MonoBehaviour
{
//Components
public Rigidbody2D playerRigid;
//Player horizontal movement
[SerializeField] private bool IsMoving;
[SerializeField] private float playerSpeedX = 0;
[SerializeField] private float playerMaxSpeedX = 3.5f;
private float playerVelocityX = 0;
//Scripts
[SerializeField] private PlayerSprite playerSprite;
private void Awake()
{
//Get Components
playerRigid = GetComponent<Rigidbody2D>();
}
//.........
In the second one, why don't you just drag the reference instead of using GetComponent
In the first one, the component is probably TMP_Text instead of TextMeshPro. But you could make that one serialized as well instead of using GetComponent
True, although it is TextMeshPro, i've just been having this trouble with multiple projects with this reference error and it even became a nightmare of a mess lol
imo dragging components is annoying when you can just use getcomponent
this would just cost performance
can someone tell me what this means?
just drag it in the inspektor and build a fallback
how? don't they do the same thing?
I've been trying to use drag components more, but before that my latest projects mostly consisted of private components
Hey everyone, how can i tell my script to replace the box prefab with another prefab? For example i want to replace the box with a rocket
no unity saves the reference. i would save some small micro perdomance
just drag a new Prefab from the Project folder in the Field
they probably mean through script
no i want to change it inGame
instead of the "Box" u can create a new Prefab from the Rockecd and put it in the Project folder
just make a other field for rockets and at runtime choose which one to use
What do you want to know ?
my bad. my englisch is chopped
No worries
@rich adder a little help pls
im also not the best but i can try to help u, what exacttly is u problem`?
I want to change the prefab while the game is running using a script
u could make a new field?
have a field for currentPrefab then fields you can drag in all the options you want for prefabs, then just reassing current prefab as needed
in the inspekor drag the prefab in and use it
if you're gonna have more than 2-3 items then its probably best to put them inside an SO
Do i REALLY have to make a new field?
i mean it would be simple
i want to know what it means. I have encountered problems before and i thought i understood what it meant but later found out that i understood it wrong. if you could tell me what it means, that would be helpful
why not?
you need a reference to the new prefab somehow, so yes thats the most straight forward way
Ok then
why fight a simple straight forward soultion. since you need atleast a way to reference all the options you want at runtime and a way to keep track of which is the current to spawn
Sure but helps if you describe, which part are you confused about ?
so that could be multiple fields or make it a array and keep a index of the current one
Because in the feature when i have like 10-20 objects i dont want to make multiple fields
u can us OS
so a array
array?
how do you know it saves performance? maybe it does some stuff under the hood to de-serialize it which makes them equal performance-wise (or maybe worse than the other method)
array could work but you have to know which index will be what object
i googled it one time
I'll just go with the simple way
i mean u can search it per runtime, i just heard that it saves a "micro" small performace when u drag it inm the Editor
you sure you found a trustworthy answer though?
only other ways are much more advanced then what you know right now like loading via addressables
definetly no
but it would make sense
would just keep it simple with multiple fields or a array and a index
make as many fields as you want, if you want to make it easier to to track you put them in a Scriptable Object
so i understand that there is a vehicle class and a navigator class. the vehicle class has defined functions such as goforward and reverse and etc and navigator calls those functions using a function called move which takes in a class vehicle as its argument. problem is that if i try to implement a class train, why does it give an error?
Yea ur right i dont need to rush things
that inheriting class doesn't work there basically, the inheriting class now has extra methods from base class which do not make sense for this derived class
i would only trust it if it was said either by someone working at unity, or praetorblue 😄
you guys are putting too much thought into this, use what ever works just be sure to only do it once and not per frame though
u decision, but why do u want even searching everthing via code the references? when u can use public? it look better in the Inspektor
just to clarify, when you mean inheriting class you are reffering to train class and when you say base class, you mean to say vehicle class, am i correct?
yes
then what do you mean by derived class or is it a synonym for inheriting class?
yknow this is not an uncommon topic
several people have stated this, and it's really straightforward if you think about it
i mean if u want deal damage to the enemy, it would be better to searching it in the code but like if u want u own ScriptReferecnes maybe a AnimationControllerScript i would use a public field and a small fallback in Awake
right they are the same
Derive from another class
or Inheriting it
GetComponent does the searching at runtime, a serialized reference does the searching at devtime
using the reference is O(1) with the id anyways (most likely)
if i want to use the script on multiple objects, then every time i add this script to an object i also have to drag some component references. dont you see the problem?
then you can use the Reset method
do getcomponent, but in Reset instead of Awake
it really does not matter if you are doing a few one time lookups on Awake i just use what is more convenient
also i often just make my OnValidate setup the ref for me if its empty
that way its automatic or i can drag something in
another example Violating LSP
public class Bird{
public virtual void Fly(){
Debug.Log("The bird is flying");
}
}
public class Penguin : Bird{
public override void Fly(){
// violates the expected behavior!
throw new NotSupportedException("Penguins can't fly!");
}
}```
Subclasses should be usable anywhere their base class is expected without breaking behavior.
worry about making the game
oh wow, i had never heard of this method before 😲
hmm not sure you should be doing that in OnValidate
not little details like this
i make a public field for the Inspektor, and in awake a fallback? what do u mean with "instead" of Awake?
you don't do it in Awake and you do it in Reset instead. that's what instead means
it's a unity message yeah
it gets called when the componet is created or when you run reset from its context menu
its only editor time
at devtime, when the component is created or when the reset button is clicked
not sure if it's also called upon AddComponent
created? per runtime?
this is usefull ashell
@tired python
bad example violating LSP ❌
class Bird { public virtual void Fly() {} }
class Penguin : Bird { public override void Fly() => throw new NotSupportedException(); }```
good example for LSP ✅
```cs
abstract class Bird { public abstract void Eat(); }
abstract class FlyingBird : Bird { public abstract void Fly(); }
class Sparrow : FlyingBird { public override void Eat(){} public override void Fly(){} }
class Penguin : Bird { public override void Eat(){} public void Swim(){} }
could you code the main part of the program which would actually run this? i understand that because bird and penguin both have a function name Fly, there is an error, i wanna know how to get this error on VS
no, at devtime, when you put it on a gameobject
there is no compiler error
looks like we both just found a better way of doing component references 😄
Definetly
i really learn allot in this dc
Awesome thank you for the info. What I wound up deciding was since I'm just using the server to relay info to other clients and am not using the authoritive server model that networked entities do not need to be game objects. I am just going to do floating point shift on client and send their reap position as a double to the server and on the server network entities will just be a struct which contains doubles for the position
make the void main() part of the code, i wanna see it run
void Main() {
Penguin penguin = new Penguin();
MakeFly(penguin);
}
void MakeFly(Bird bird) {
bird.Fly();
}
doesn't sparrow which inherites the properties of flying bird which in turn inherites the properties of bird produce and error?
what is the error you're thinking of here
both of them have eat() function in here, so when you call eat(), the compiler doesn't know which one it's supposed to call?
that's what override is for
oh
overrid prioritises a specific function i guess?
even though multiple classes have Eat(), each overrides the base abstract method.
the compiler checks the method exists (Bird.Eat()).
at runtime, C# calls the correct version based on the actual object type (Sparrow or Penguin)
wait i just realized, what if i already have this script in a bunch of places and then i add a new getcomponent call into the reset method? is there a global reset button or would i be screwed?
you would not want to globally reset
that would remove all your other configured values
this is probably something you'd need to have foresight with
how do i see an output on vs when i am using console to print stuff?
just use the console in unity
tell me both then
Debug.Log
ya but like where does it show?
The debug log
in the Unity console tab / window
in...vs
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
no it doesn't show in VS
Debug Log should literally be the first line of Unity code you ever wrote
Why would it? You don't run code in VS
If you had a console app sure it makes a Console.Writeline output in a new terminal window but in Unity is just easier to use Debug.Log
did you import unityengine
Do you actually have the Unity namespaces included
class BaseClass
{
public void Method1()
{
Debug.Log("Base - Method1");
}
}
class DerivedClass : BaseClass
{
public void Method2()
{
Debug.Log("Derived - Method2");
}
}
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
DerivedClass dc = new DerivedClass();
BaseClass bcdc = new DerivedClass();
bc.Method1();
dc.Method1();
dc.Method2();
bcdc.Method1();
}
// Output:
// Base - Method1
// Base - Method1
// Derived - Method2
// Base - Method1
}```
this is the code i am trying to upload
!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.
And no, you don't
why not just use like, C# online for that
So how would you expect to use any Unity functions
then, you could use Console.WriteLine
Also main isn't going to work in Unity
dotnetfiddle
Well, you can make a main function but you'd need to call it like any other function
you can google any well known language plus the word "online" and get an online runner/interpreter/compiler/etc
Test your C# code online with .NET Fiddle code editor.
it's not like cpp at all
it is
in what way
just that the context of unity isn't like individual executables
where's main where's cout
Console.WriteLine
I’m developing a 2D mobile game in Unity (URP)
I’m currently trying to make my Jelly objects feel more realistic and “gelatinous”, both visually and physically — soft, bouncy, and satisfying to watch — while keeping performance stable on mobile some advice
Unity doesn't use main or Console.WriteLine
cout is specific to c++, but the main is still similar. it's the context of unity that isn't the same
okay ?
It's called Softbody Physics. It's fairly complicated stuff and not supported out of the box, you'll need to roll your own or find an asset for it
on unity ?
make a bunch of points, connect said points. Now you got a softbody (obv there is more to that)
wot
maybe look what other people made https://github.com/Ideefixze/Softbodies @uncut tide
thank you
Console comes from System - you need a using statement
oh
is there asset to use ??
probably?
perhaps look up some c# tutorials if you want to explore c# on its own
there are some pinned in this channel
@tired python
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
in c#?
you can make a namespace anywhere
then what do you do if you wanna add more functions in general?
you just add them to the class/struct
I thought soft work just for 3d Am a beginner don't mind if I ask some simple thinks
You write them
no you can make 2D softbodies too . There's plenty of examples / assets online. Did you research this topic at all ?
c# is oop-based, so it doesn't have globals. methods/variables exist inside types.
types exist inside namespaces - the global namespace, if none is specified.
yes I see a video I find a asset in unity library but he make my programme crash so I decide to makeit myself so why am here
it does not
IDEs do not run code
they may integrate things that actually run code - interpreters or compilers+executables
i mean yeah, but if you do connect it to compilers, they do
but it isn't doing the execution itself
this is true for any tool - discord can run code if you consider that as the tool doing it itself
so vs can do that right?
sure, but not with a unity project
no
unity has a specific context in which it runs
c# can run just fine. other languages can run just fine
aight i understand
other systems/contexts that expose that context can run too
unity does not, so it can't be run separately
i do remember getting the .net framework along with c# installed while downloading this vs. how do i use it then? because the way it is rn, my vs is basically acting like a notepad...it can't run stuff or even if it does, i don't really know abt it cus it's not outputting smth somewhere
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
sounds like it might not be configured ^
though.. i don't remember these steps for vs. you sure it isn't vscode?
You can test all the same stuff in unity using Debug.Log
you can use Start or Awake as the entry point
i had vscode before i formatted. a dev told me that if i wanna try modding, i might wanna use vs. i formated my pc and rn i only have vs installed. i do have mingw and python installed on my other drives
i understand that that's a way to do stuff but i might just not wanna run it using unity cus i might wanna use other languages as well
so why are you asking c# questions in a unity coding channel
so i should only be asking stuff here if my code requires using unity?
Ask questions and discuss anything related to beginner coding concepts in Unity
if you want to talk general / basic & c# apps you should do it in the C# server I linked
oh i did not see that prolly sry my mistake
could you share the link again? can't seem to find it in your msglog
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
so like what unity is to c# is basically what arduino is like to cpp?
Not really
Unity is just an API
uses c# to communicate with its C++ backend
its an engine, so it already has its own implenetations of Physics etc.
Arduino is a microcontroller that runs on C / Cpp code
Software vs Hardware, unity is not hardware
i mean.. honestly, i wouldn't say it's that much off
I'm just not sure what sort of useful insight is to be gained off of comparing the two
Arduino just simplifies not having to buy a Devboard for programming a chip
c#/cpp are languages, unity/arduino are specific contexts that use said language with a specific library and specific constraints to interface with a system
the specific context/library/constraints/system part are vastly different, as described above, though
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
plenty there, and plenty on youtube
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
oh boy..
what did you think that would do
Why use the bot again the response is like two messages up
Hey guys can sombody give me a recomendation about how to hit only one time a enemy and allowing 2 enemys getting hit with one Swing?. i dont know how to approuch this?, i tridy it but every time it gets messy and dont really clean also really dont working. im currently try to improve my skills => ```cs using UnityEngine;
using System.Collections.Generic;
[RequireComponent(typeof(Collider2D))]
public class DoDamage : MonoBehaviour
{
[Header("References")]
[SerializeField] private CombatSystem combatSystemScriptRef;
[SerializeField] private Collider2D LightAttackTrigger;
[Header("Light Attack Settings")]
[SerializeField] private bool allowDamageApply = true;
[SerializeField] private float baseDamage = 100f;
[SerializeField] private float LightAttackDamage = 10f;
[SerializeField] private float HeavyAttackDamage = 30f;
void Awake()
{
if (LightAttackTrigger == null) LightAttackTrigger = this.GetComponent<Collider2D>();
if (combatSystemScriptRef == null) combatSystemScriptRef = this.GetComponentInParent<CombatSystem>();
}
private void OnTriggerEnter2D(Collider2D other)
{
if (!allowDamageApply) return;
SetDamage();
if (other.gameObject.CompareTag("Enemy"))
{
Debug.Log("der aktuelle Schaden ist" + baseDamage + "");
var enemyHealth = other.gameObject.GetComponent<BaseEnemyHealth>();
enemyHealth.TakeDamage(baseDamage);
}
}
private void SetDamage()
{
baseDamage = (combatSystemScriptRef.currentAttackMode == CombatSystem.AMode.Light) ? LightAttackDamage : HeavyAttackDamage;
}
}
i don't wanna sound like a dummy to people in the future who might ask me related stuff....
saying "i don't know" is a perfectly acceptable answer
what's the harm in knowing though
(which is why genai is such a pain to deal with in educational contexts. it always has an answer, even if it's completely wrong)
dunno
these kinds of things can... open up vast cans of worms
"did I do good boss, did I do good" 🐶 🦴
hey i need to make it so that my player can pass through the enemy but they all get stuck on each other as its like brick wall i just like it to pass through the enemy this should be simple but i cant find a tut on it
like in silk song you can pass throuth the enemy
its 2D
i think u can use matix collision?
ive heard of it but what boxex do i uncheck
i mean if u would disable the colliders of the enemy they would fall out of the map?
yeah
you need them in different layers
they are
so uncheck the two layers you dont want to collide
ohh
uncheck the player and the enemy layer
so they dont effect each other
in matrix right
i dont really know im also new
if you want them to be permanent yes
i will try
there is also Physics2D.IgnoreCollision and Physics2D.IgnoreLayerCollision for run time
the former needing a reference to colliders you want
nav? can u help me with code i posted befor?
which code ? its not showing ffor me on mobile
use pastelink site
📃 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.
A tool for sharing your source code with the world!
this is the code? can u tell me how to build this modular? i want to hit multiple Enemys at ounche but only one time per enemy for a small duraction..
wich box this is confusing
You could probably use a hashset
hasset? i need to do a resarch
but thank u!!
do i just test each one with player and enemy
just have a collection where you store the enemies, if the collection doesnt contain the enemy then do something
something similar to a list but does not store duplicates, so you can store the enemies that got hit once and skip if it got hit already
will check
im really not sure but maybe this =>
uncheck the enemy box in the first player column.
i was actually referring to Bad_GameDev
to me ?#
AHHH Ha collection... i understand but i need to look about the syntax
i thought u mean Swetpig hahaha
you ever use a List ?
its the same exact thing
except you cannot store duplicate items
myList.Add () etc
HashSet<Enemy>() enemiesHit = new()
Overlap or something like that
foreach enemy in enemies
if( enemies.contains(enemy)) continue // skip
[SerializeField] private List<Collider2D> colliders;
i only use somthing like that?
it wont detect the enemys damage if i seperate there layers
are you using player colliding with enemy as damage ?
yeah that
but normally I make a sepearate Layer for Damages
you might have to add a childobject to both the player and enemy that has just a box collider as a trigger.
this way i can separate solid body from trigger damages
yes
I would make a seperate layer for trigger damage so you can seeperate the two
is that easy
easiest way i can think of right now lol
this way you can use the Damage trigger layer for other hurtzones
is there a tut on it
yeah i saw a good one on yotube
ohh
idk a specific tutorial, its easy though
put a trigger on the enemy, then use OnTriggerEnter to damage player
(the have to be on sepearate gameobjects and let the player detect the trigger)
just type matrix collidion u should find
ok
Iirc you can also keep colliders on the same gameobject and use the features on the Colliders but I havent used those much
Sweetpig did u create the art by u self?
one for trigger and one for solid
yes i was inspired by silk song after playing love the game
give it me personal via dm
okay
we would rather you not go to DMs
why?
ah whoops thought yall were talking about a video about an issue
did not backread far enough
yeah for issues we'd rather you keep it here because that's kinda the point of a community server - to have multiple people available to check or help or proofread other answers
we talking about a twitter link
can we share links here
if youre sharing just to showcase game progress and or assets you can use #🏆┃daily-win or #1180170818983051344
otherwise the links have to directly be something related to an issue or a question you might have
ohh okay
Hello, can anyone help me with my current issue in my 2d unity game. The main problem I'm running into is setting up invisible barriers to make it so that the player can't escape the games boundaries. Here's the setup:
- Player game objects Rigidbody 2d set to kinematic and a box collider with set trigger = false
- Wall game objects having a static rigidbody 2d + box collider with the same set trigger value.
The player can still walk straight through them and I have no idea how to fix it. Here are some screenshots as well as some code for context:
private void HandleInput()
{
if (!isDashing && canMove)
{
moveInput = Vector2.zero;
if (Input.GetKey(KeyCode.W)) moveInput.y += 1;
if (Input.GetKey(KeyCode.S)) moveInput.y -= 1;
if (Input.GetKey(KeyCode.D))
{
moveInput.x += 1;
spriteRenderer.flipX = false;
}
if (Input.GetKey(KeyCode.A))
{
moveInput.x -= 1;
spriteRenderer.flipX = true;
}
if (moveInput != Vector2.zero)
{
moveDirection = moveInput.normalized;
lastMoveDirection = moveDirection;
float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
Aim.transform.rotation = Quaternion.Euler(0, 0, angle);
}
else
{
moveDirection = Vector2.zero;
}
if (Input.GetKeyDown(KeyCode.LeftShift) && dashCooldownTimer <= 0f)
{
StartDash();
}
}
else if (!canMove)
{
moveDirection = Vector2.zero;
}
}
public void HandleMovement()
{
if (!isDashing && canMove)
{
if (moveDirection != Vector2.zero)
{
Vector2 targetPosition = rb.position + moveDirection * moveSpeed * Time.fixedDeltaTime;
rb.MovePosition(targetPosition);
animator.SetBool("isMoving", true);
}
else
{
animator.SetBool("isMoving", false);
}
}
else if (isDashing)
{
Vector2 dashVector = lastMoveDirection;
Vector2 dashDisplacement = lastMoveDirection * dashSpeed * Time.fixedDeltaTime;
rb.MovePosition(rb.position + dashDisplacement);
dashTimeRemaining -= Time.fixedDeltaTime;
if (dashTimeRemaining <= 0f)
{
StopDash();
}
}
}```
is it walking through all of the time or only some of the time? if it's random it might be because you are trying to set the position of rigidBody outside of the FixedUpdate possibly but if it's all of the time it's probably an issue with your collider / physics matrix setup.
rb.MovePosition will teleport through walls
its walking through all the time
which one should I be using?
.velocity or use rb.sweeptest + rb.cast to detect walls and not allow movement in that direction
should I still use .velocity, i've seen that it's been depricated
use the new linearVelocity
if you're ever curious how the other suggestions i made works, check out a good example here (timestamped)
https://youtu.be/7iYWpzL9GkM?t=2202
Guide on many of the first steps building up a top down 2d pixel art RPG from scratch in Unity 2022 version. The goal of this crash course is to cover as many relevant beginners topics as we can but linked together in actually building out some prototype mechanics for a potential game.
For the video, I'm using this mystic woods pack for this tu...
I updated my code to do only linear velocity but the player is still going through?
Should I try using transform.Translate instead?
you'd have to make it non-kinematic
no thats like teleporting, even worse
the only one that's set to kinematic is the player
should the player be dynamic?
ahh
yes he should
yes. If you use kinematic then you'd use MovePosition with the rb.Cast like the example in the video
is there such thing as a reduction algorithm that can make those big flat faces into 2 triangles intead of a ton of triangles?
well in the case of a cube like this, a convex hull would do it or even getting its bounding box and making a mesh from it. but aside from that most 3d packages do have mesh decimation tools
i feel like a simple quad remesh in blender could cut this down into 16ish quads.
How do I add a range to a list? I'm trying to make a dice system with lists just out of curiosity, but it seems like I'm going to have to do
_numbers.Add(1);
_numbers.Add(2);
_numbers.Add(3);
_numbers.Add(4);```
So on and so forth until I get to 20, which is fine tbh, but is there any way to make it more efficient and just create a list from 1 to 20 without 20 lines?
its not a game asset its procedural existing only in memory
And I can use a for statement to add a range to a list, or is adding a range to a list not possible efficiency and using a for statement is just easier?
Depends what you mean by "efficiency"
In this case, able to write _numbers.Add(x-y); instead of writing _numbers.Add(x) for every single number
Or however the code works
Condensing however many lines into just one or two maybe
add a range means something different in context of a List btw
like
List<int>myList = new();
myList.AddRange( 5,6,7,8);```
"range" in a collection just means multiple consecutive elements
you could also get fancy with enumerables
myList.AddRange(Enumerable.Range(1,20))
That seems to do what I want, but when I plug _numbers into a debug.log just to see if it's working I get this outcome
foreach(var number in _numbers) Debug.Log(number)
It probably is, but I want the ability to add weight to certain percentile ranges and lists seems like the best way to do that.
Like if I had a D20 but I want it to have a higher chance of landing on D16-D18
use whatever works for your usecase, the difference are marginal
the way I suggested is just a shortcut for a for loop, in any case
it just looks a bit nicer
ya looks clearner but they both pretty much do the same thing loll
and probably a bit slower, but irrelevant in this case
Yeah this is being used for just a number generator, so speed isn't a concern
you can also do this _numbers.ForEach(num => Debug.Log(num)); but again same thing, just inline-ish
or join
also
Debug.Log(string.Join(',', myList));
Alright yeah that works, but I'm getting the entire range now
Not just one number
Debug.Log(_numbers[Random.Range(0, _numbers.Count)]);
So if I were to start it again, I'd get a different one
Length has a red line under it
basic c# stuff
var randomIndex = Random.Range(0, _numbers.Count)
var randomNumber = _numbers[randomIndex]
sorry lists use Count
arrays use Length cause they're fixed.
Okay so, something weird, I'm getting random numbers now which is good, but 14 random numbers instead of just 1
show what you wrote
you put it in the loop or something
yea u are doing that as many times as numbers in your numbers list
put it out of the foreach if you dont want to do it as many times
it adds all numbers from 1,20
ah beat me to it ^
Thank u g