#π»βcode-beginner
1 messages Β· Page 351 of 1
you paid then? You have to just pay for a premium account right?
yep its not abt the dialogue itslf, but the triggers, like speaking to an npc, entering a scene, stepping into a certain area, getting an item... ecc ecc...
(the trickiest part is the one that checks if the player has achieved X things in the story)
I don't have lfs on as my files aren't >100mb each
Even though the repository is 26gb
I meant for disabling pushing to main
There's a setting in GitHub for that uh
Branch protection
Yuh
Yea you can't enable it with a regular repo
well if that isn't present then i wouldn't consider it a real dialog system
more of fluff at that point π
Box collider with trigger
Attach a script that takes in a serializable object where on trigger enter, it plays the lines stated in the serializable object
Also that's still really large.... i'd say over 15-20mb it should be added to lfs. We baked lighting though, so we had one file that was like almost 2 GB lol.
Total project size for us: 58 GB
Build size: 2 GB
And also track that the dialogue has already been played before in your save file
School project so I don't really care what GitHub thinks
We don't even bundle our assets
You say that and then one of your files you pushed gets corrupted or something
Hasn't happend yet
You regularly bundle your assets?
Tbf I've never made a project large enough to justify bundling my assets
whats bundling ur assets mean?
Even my genshin ripoff was only 400mb despite having a lengthy campaign
yessir i agree, but what if i need a dialogue to trigger under super specific conditions? do i just make a personalized script? Is a bunch of ifs the best way?
simple trigger colliders.. that call a function within ur DialogManager class
let's say you're making genshin impact, big open world RPG with lots of assets.
but you can't load 60gb of assets at once
to bundle your assets means to place them in files that get loaded at different times. if you're in one region then the files for that region get loaded and the rest remains unloaded to save ram
It's very important for console because consoles have very little ram π‘
NPC: Billy VISIT: #4
ohh okay.. yea makes sense
AAA kinda stuff
Loading Shaders
also helpful for sharding downloads for your game
Oh we're talking about Addressables here huh?
just a brief summary
/woosh
I haven't touched it much because I don't make big game
that 1 thing i haven't even had secondary exposure to
Everything I have is low poly
Same! π€ π€
including my skibidi toilet fan game
lowpoly-ftw
not b/c i can't model..
but b/c i can't texture π
I would probably suggest using the newer Addressables system rather than asset bundles directly
I feel like my method is hard coded but yea having triggers that read scriptable objects for dialogue does wonders
Substance Painter go brr
well, i can texture.. but im bad at UV mapping
womp womp
wanna hook me up with a subscription π
theres 1 that u can compile urself for free i believe
no cus i dont have one lol
ArmorPaint
Tldr I have QuestManager.AddObjective, either takes in Dialogue which plays dialogue, Position which places a marker and asks players to go to a location, Entity which asks player to kill enemy(ies) and Puzzle
This Quest manager is independent of CampaignManager
https://armorpaint.org/ this one is free if u compile it yourself π
sounds solid
this is fine imo
I enjoy low poly games a lot
ya, im growing tired of flat shaded models tho..
as a Roblox child
i'd like to adda bit of texture here and ther..
can't you texture in unity?
if you're daring enough you can make submeshes and do the base map in unity
not the texturing.. but the UV mapping
just havent learned enough yet to be good at it
you can start small ig make submesh for the walls of the barn and put some stock texture
I don't really 3d model I just paste cubes in the scene and call it a day
https://www.thebasemesh.com/ not sure if ur familiar. but this is a great asset
all of these come with great UV's
Ooh
Right now I'm using Womp3D for my more complicated models
Very fast to get into
thats what i use to practice my texturing for now... and once i feel comfortable doing that.. i'll have more context to use myself.. when trying to layout good UVs
b/c its not that i can't UV its more like I don't know what good UV's should look like..
i'll just Smart UV unwrap everything! π€£
sounds revolutionary
but anywho, i believe we've went offtopic a bit π€
π€« i'll be quiet.. just waiting for some code related questions lol
right now I'm thinking of server side implementation to store user data, I'm making a small project right now and am lazy to set up firebase
how secure is making an in-memory database in python flask? user passwords will be hashed with bcrypt
i'll probably just try to contend with this error for a while
i've never used flask for anything but webdev
does it have an API that unity can use?
well is anything ever actually secure?
i do know 1 thing.. server-side is hella lot better than client side
soo u got that going for ya
soo basiclly a www web request type thing?
Yep
i haven't much experience with those outside of setting up a Mirror lobby
i should experiment myself
the database
Dictionary<int, string> passwords; // user passwords hashed with bcrypt
Dictionary<int, Inventory>; // user's inventory
struct Inventory {
int coins;
List<item>
}
in theory this is secure
but people absolutely despise me for this implementation
why is that?
no one uses flask to make an actual backend they keep saying it's for learning purposes
and to go use a proper backend
private static IEnumerator LoadGame(GameStateModel modelToLoad)
{
var operation = SceneManager.LoadSceneAsync(modelToLoad.CurrentSceneName);
while (!operation.isDone)
{
yield return null;
}
GameSaveService.LoadGameState(modelToLoad.FileNameWithoutExtension);
}
Is there a way to do this statically
Because StartCoroutine does not exist in a static context
you want to do this across scenes?
you can start the coroutine from a non-static method on a MonoBehaviour, such as in response to pressing a Play button
This object will die during the scene switch
Put it in donotdestroy
I do want it from a static context
β
But StartCoroutine does not exist
you can make a public static instance though
why
Easy service integration
If there's no way to make it static that's ok
Just making sure
then either make a persistent gameobject that you can start the coroutine from or don't use a coroutine
Do I HAVE to use a coroutine for just "waiting" while loading?
public class GameLoader:MonoBehaviour {
public static GameLoader instance
Start() {
DoNotDestroy
}
public IEnumerator LoadGame() {
}
}
smth like this
I know what a singleton is haha
depends, are you using Unity 2023 or newer?
then just Start routineGameLoader.Instancr.LoadGame())
22 LTS
then the only built in option for waiting for that load to complete is a coroutine
in addition to loading scene async you can also load it additively, then once it's done you can unload the main menu
stuff might explode though last time I tried it the engine didn't like me
I'm ngl a lot of loading screens are fake
If you're not loading 8gb of assets or waiting for other players to join you can fake a loading screen
just write a static class that will spawn a gameobject with a component that just starts the coroutine on it and marks itself as DDOL. then the static class just keeps the reference to that spawned object for the duration of the session and you can change scenes using that
or you could use a singleton, but that would require putting it in a scene manually or lazy loading it which is basically the same thing i just described anyway
i personally prefer the static class option because then the monobehaviour can be private so nothing can access it directly without some wacky shit like Find
imagine using Find in production
can anyone help me figure out why my enemy movement script is not working?
my enemy keeps just moving up and down and does not follow the player at all :((( i've set up the entire enemy script and everything works correctly apart from moving the enemy
what is the target field assigned to
you're setting your own RB velocity when trying to move the enemy
Vector2 direction = (target - (Vector2)transform.position).normalized;```
but yeah it's unclear which script this is
or what object it's attached to
or what the variables are assigned to
etc
i think i found it as i sent the message it's so dumb im ashamed of saying what it was

whats wrong with that?
IEnumerator BootEnvironments()
{
FindLightController();
yield return GetRandomWaitTime();
environmentProgress = 100f;
IncrementSector();
}
IEnumerator BootSystems()
{
FindGamePlayObjects();
SetupSettings();
yield return GetRandomWaitTime();
systemsProgress = 100f;
IncrementSector();
}
IEnumerator BootGameSetup()
{
SetupPlayer();
yield return GetRandomWaitTime();
gameSetupProgress = 100f;
IncrementSector();
}``` π
eventually i wont need to fake it π€£
but u can tell from the video its soo fast.. b/c i reduced the GetRandomWaitTime() to zero
how can i check if a value is going down in an if statement?
cause if(value--) doesnt work
if (value < previousValue)
that will just check if a value is smaller then another value
yes
and if that "other value" is the previous value of the variable
then we know it's "going down"
you asked quite a vague question btw, so I'm answering to the best of my ability with the given context, which was basically 0
ok leme explain more
You mean to say that if the value now is less than the value last frame?
int coins;
int coinsLastFrame;
Update() {
if(coins < coinsLastFrame) {
}
// other logic
coinsLastFrame= coins // make sure this is last
}
depends on what you're doing
Yes^ in other words if (value < previousValue)
but if this really doesn't answer the question, more context would be nice.
im having an error that says that addforce doesnt take 4 arguments, what sintaxis error am i having? i searched in the docs and couldnt find it or dont understand it
You're looking at the docs for Rigidbody
this is a Rigidbody2D
it takes in a Vector3 not 3 floats
do check the examples
Also you're supposed to give direction of force in vector format, not separate floats
Rigidbody2D takes two arguments for AddForce: Vector2 and ForceMode2D
private IEnumerator LoadGame(GameStateModel modelToLoad)
{
Debug.Log("loading");
var operation = SceneManager.LoadSceneAsync(modelToLoad.CurrentSceneName);
operation.allowSceneActivation = true;
while (!operation.isDone) yield return null;
Debug.Log("finished");
GameSaveService.LoadGameState(modelToLoad.FileNameWithoutExtension);
}
"loading" is printed and the scene changes correctly, however, "finished" is never printed, nor is the method unterneath it called. Why?
https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html Always check docs @radiant frigate
scene dies before finished is printed
thanks everyone ill check!
you can load it additively
You are probably running this coroutine on a GameObject in the previous scene and since you didn't load the new scene additively, this object went byebye
then unload after finish is printed
Ah so I can simply transfer it to a DDOL object?
You need to either load additively or this object needs to be DDOL
oh nvm the hting i needed fixed itself out
suspicious
i mean if(value--) was certainly pretty confusing
im adding sprinting and i wanted to make it so when a person is running or jumping to set the regentimer to 5
and idk why i came to check if the stamina value is going down
basically you actually wanted to know if you were sprinting, you thought you could do this by checking if stamina was going down, but really you should just be checking your isSprinting variable or whatever
oh
yeo
yep
idk i confuse myself when i am reworking on my own code, so sometimes if i just reread the code then i can easily do it
tysm!
Hey guys, I just wrote a script to spawn a prefab within this range, but it's not spawning anything. Does anyone know why? Yep, the object has a collider and is prefabbed
Is the code running? Make sure with Debug.Log
True :p
Unless that function is hooked up to an event (like a button click), the "0 references" on top of that in the code should be pretty self-explanatory :)
okay i added force but now he just phases through the wall, i could make a hitbox to tp in him back again but i just wanted to ask if there is something smarter that wont lead me to having to do this each time i use addforce
Which object are we talking about?
The spaceman?
yes
You just need to make sure its colliders are properly arranged
looks like the sprite and collider are not aligned properly
if i allign it it shouldnt phase through the wall?
for the spaceman could you show the collider
of course
like the circle collider attached to it
I just added this, but the script won't even run... That's weird
this should work then right?
and the collider for the wall?
Well do you have an event system in the scene? What kind of object is this script attached to?
Is that script on a UI object (under a Canvas)? Do you have an Event System in the scene? Does that have a Graphics Raycaster attached to it?
i think the collider is directly related to the grid so i shouldnt or maybe even cant change that
but i might be wrong
you can change it
it's from the tiles
and the colliders for the tile sprites can be configured in the sprite editor
make sure the collision shape is correct for the tiles
It's on this game object 
so it's a physical game world object? Does your camera has a PhysicsRaycaster2D?
and again, do you have an event system in the scene
I cant look up or down is there something wrong with my code? https://paste.ofcode.org/yKdjLnwaFD38szFjp7yjr8
but even if it were wrong wouldnt it just stop at the collider point
something like this
where even if the sprites where overlaping
the colliders arent
well for one xRotation -= mouse_Y * verticalSensitivity * Time.deltaTime; you should not be multiplying deltaTime in here
No I don't 
but it's more likely an issue of how you set things up in the inspector
well you need one
and also the physics raycaster2d on the camera
How do I add an even system? I'm a little unfamiliar with that
so shall I get rid of Time.deltaTime?
yes in both places, but again that's likely only one of your problems.
you probably didn't put the script on the right object or your objects are not arranged properly in the hierarchy etc.
In the Hierarchy, under the right-click > Create menu
this isn't relevant to our discussion
the sprite editor for the individual sprite is where you'd set the physics shape
and your wall too
Under the right click?
Yeah when you right-click in the Hierarchy
looks like you're using a rule tile to just spawn a prefab
so you'd have to show that prefab
as that will be a separate GameObject and won't be related to the Tilemap collider really
There's no "create menu"
ill just try
I mean the tile map collider should cover that but
I forgot how it's called. "GameObject" maybe? There aren't many options, look through all
instead of using a normal tile
because im a begginer and dont know any other way
this was what made the most sense to me
since it wouldnt let me just choose the square sprite as default i created a gameobject that was just the sprite
I recommend investing in this short tutorial to learn how to use tilemaps https://learn.unity.com/tutorial/introduction-to-tilemaps
Unityβs Tilemap system makes it easy to create and iterate level design cycles within Unity. It allows artists and designers to rapidly prototype when building 2D game worlds. In this tutorial, you'll create a Tilemap and explore the Tilemap system including Tilemap settings, and you'll use the Tile Palette to edit your Tilemap.
UI > Event System
Seems like they pulled all the options up to the root menu itself
And grouped them up better
Do I really need an Event system? Since I'm not using nothing from the UI section
I mean just have it in
Yes, that is what detects objects and dispatches events to scripts
It's not that expensive
you are using the event system if you want to use PointerClickHandler
That's part of the event system
aa oki
You'll need a Physics Raycaster on the camera too
2d*
π
never a good thing
i read it and i now created a sprite in my assets which is now with what i draw
and it has collision thanks to the tilemap collider
but i still phase through it
You already had the sprite I thought. This was more a question of using a Tile vs a GameObject
So you owuld have added the tile to a tile palette
yes i added the tile to a tile palette
should i have just placed a bunch of gameobjects as walls?
srry im not understanding what the problem is now
look at the colliders
its in chunk mode
and its well represented i think
the yellow part is the collider
or should be
the green outlines are the collider
it's common to combine that with a Composite Collider2D btw
regardless, this should be alright so - back to the player
Also make sure your camera is head-on. Are you in 2D mode?
yes
can you show your code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
this code isn't really adding forces it's just setting velocity, btw
if ur setting the velocity every frame (b/c of movement) adding forces isn't going to do anything
you'll just reset them the next frame
the collision part isn't going to matter because Update is overwriting the velocity every frame entirely
π
so i should addforce instead of .velocity?
Not necessarily
i mean basically it has nothing to do with the problem you're talking about
okay i will give some context of why i did things so maybe that helps you help me
at first whenever i collide with the ball it would slow down, so what i made was that whenever i collide with it, it just sends me back
and the way i thought of doing this was with .velocity
but it didnt work, so i tried with addforce and it kinda works, the problem is that i now phase through the walls
π€«
neither of those should phase through walls
should i try to change to addForce instead of velocity
it won't make a difference
because since it resets each time for it to impact it has to be very high in the only frame it acts, so maybe by changing it to addforce i can lower it and make it so it doesnt have the speed to phase?
it has to be an issue with your colliders
one workaround is to pause ur player's movement code for the knockback to take affect..
then after a short delay.. reenable it
a couroutine?
private IEnumerator ResumeMovementAfterKnockback()
{
yield return new WaitForSeconds(0.2f); // Adjust as needed
allowMovement = true;
}
``` yes a coroutine could probably achieve that
but that would be the same as making my character work with addforce right?
well not completely
but in that aspect
Knockback(){
allowMovement = false;
rb.AddForce(knockbackforce);
StartCoroutine(ResumeMovementAfterKnockback());}```
if u use addforce ur gonna have to add in a little bit more calculation
Again ultimately adding forces and setting velocity will move the object via velocity
so it doesn't matter which one you use
u can't continually addforce or ur player would keep speeding up
it won't change this problem of overlapping
but iΒ΄ve checked the colliders and they seem to be working
you should pause the game when it's happening and closely inspect the obejcts and their colliders
showing your Rigidbody inspector might help too
turn collision detection to Continuous that might help a little
and turn on interpolation (set to interpolate) to make the movement smoother
what does interpolate do?
makes the motion look smoother
it will be naturally stuttery because physics runs at a fixed framerate
Pretty much for any moving Rigidbody
or is there a situation where its detrimental ?
it has a small performance cost but for a single object and especially the player object it's worth it.
Is there a go-to guide for when I should be using a scriptable object? Technically everything in the entire game can be one right?
Another workaround is if ur knockback affects 1 axis.. that ur movement doesn't for example its common in here to see:
- players being moved with velocity
- jump being added with AddForce
in that circumstance there a work around where u feed the Y velocity into ur movement function.. so the movement function is not affecting the axis that u apply the forces to.. playerRB.velocity = new Vector3(0f, rb.velocity.y, 0f);
just another tidbit of information that might be beneficial to know..
No, everything in the game cannot be a ScriptableObject.
You will need a presentation layer of some kind
Either GameObjects or Entities
okay it was the collision detection mode
Ah gotcha, I'm confused on when to make one and for what purpose really
when you want to create data assets that you can create and edit in the Unity Editor and read in your code
all this data is read-only data.. my player controller just uses it to set up the controller
Everything is ruined and now I have to make a new project π¦
!vc
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
Thanks to you both again, I'm a bit new to SO's and DOTS concepts. So if I understand it right, while I could use a class with my variables to initialize and set values, the SO comes in as a way to save it to a file for later reads?
So I would have a scriptable object that holds player data, map data, items, etc
yea, but u wouldn't necessarily use them to save data to a file that gets read later..
thats more of a job for a JSON type text system
If you need to save ScriptableObject data to a file for later use, you would typically serialize the data to a file using Unity's serialization system (e.g., using BinaryFormatter, JSONUtility, PlayerPrefs, etc.) and then deserialize it when needed..
they're not typically used for persistent data
eh dont use BinaryFormatter (unsafe)
if you must use BinaryWriter
Oooh I think I get it now, basically it moves it outside of memory so that other things like prefabs that are instantiated a hundred times can access the values stored in there vs making new memory spots per instance
hi
is there a way to spawn an object randomly within a certain range?
for example: i want to spawn object X between these 2 lines, and that no matter what the size of object X is, it will always be between these 2 lines (no clipping)
yup. use something like Random.Range
u can take the size of the object into account
and just subtract half of it from the min
and half of it from the max
wow thanks
well i mean Add half of it to the min and Subtract half of it from the max, but u got the idea
yeah
exactly! u can define a reusuable data structure that can be accessed by multiple gameobjects, instances, etc, this can be helpful when u want objects to share the same data without duplicating it in memory..
so stats for a gun in a shooter game for example
What was said above, and I also like to use this struct I've created some time ago. Not sure if it helps you.
u should make it an extension to the Random.Range class π
Random.Range(min,max,sizeOfObject);
lol
Great idea, I will make it in some time when will need to use it again
Haven't used it in a while, found in the old code
i been working my way up to extension methods
starting with my own static classes.. and then once i feel comfortable i'll start using predefined classes to add to
Why don't you implement the Up?
Also you know that ternary operators are cool?
ofc i do!
using Input = UnityEngine.Input;
return held ? Input.GetMouseButton(0) : Input.GetMouseButtonDown(0);
imma change it right now π
Damn, isn't that the same code you've provided some time ago?
Shouldn't you have changed it to the lambda switch?
lol.. when i showed my previous switch statement and said it was ugly?
i did the reverse
ohh yea.. lambda switch
nah, i hadnt tried that yet
ofc, imma tie the two together sometime.. right now its just a public enum called Direction..
[this is my response from 2 weeks ago](#π»βcode-beginner message)
but i'd like it to return the direction.. but to do that imma need to pass in the gameobject first
so i can get the correct local transforms
lmao.. eyes still bleeding i guess
Now the right one
haha.. i apologize
That's alright, I've almost recovered
lmao ahh, good memory then π
It's not, you usually don't forget something that makes your eye bleed fast
like what ChatGPT tried to feed me earlier
c'mon! (β―Β°β‘Β°)β―οΈ΅ β»ββ»
when I'm refactoring I always like to get ChatGPT to make me chuckle first
never fails
ChatGPT is definitely going to throw a few errors and skip a few parts of the code when refactoring
oh yea, im very aware.. its like coaching a toddler
However, this ternary operators will make even ChatGPT chuckle 
Why can't I put any game objects inside of this prefab?
Prefabs cannot reference the objects from the scene
Oh
I tried fixing it with this, but it still won't work
-
- Are you sure the objects with the tags
TopLeftandBottomRightexist in the current scene?
- Are you sure the objects with the tags
-
- Are you sure they're enabled?
ya, its enabled and tags
I mean, you don't expect Start to run on the prefab, do you?
If you want the Start method to run, you'll have to make sure the object is in the scene. The Unity methods don't run on the prefabs.
So here's how it works: I have this game card. When you press the game card, it spawns an Egg, and the Egg prefab hatches a chicken. Up until then, everything works fine. The problem is, the chicken prefab can't contain any game objects inside
Maybe that helps clarify some things because I'm a little confused ngl

you should probably be passing a reference to the spawn area to the chicken when you spawn it
so it can know where to spawn its babies
It should already work the way it is 
It's so cute
As PraetorBlue mentioned, simply pass the objects needed for the card when instantiating it
What does that mean?

When you instantiate the card, assign its variables needed, assuming they differ when spawning different cards
give the chicken script a function like:
public void SetupSpawnArea(Transform tl, Transform br)``` and just call that after you spawn it
instantiatedPrefab = Instantiate(prefab)
instantiatedPrefab.someVariable = 10
More generally it would probably be good if there was a "CardPlatform" script or something
that you generically pass to every card you spawn
and contains all that information
yup, i concur
Cards? I'm a lil confused, I feel like we're not exactly on the same page π
whatever this is
aw how cute .
And you would usually make a struct for the variables required
whatever you want to call it
chicken? xd
when you spawn it, you should pass it a reference to the platform it will live on
how about that.. big blanket term
noo memes k thx bye

public class Chicken : MonoBehaviour
{
public void Initialize(GameObject ground)
{
Debug.Log($"Chicken spawned on: {ground.name}");
}
}
public class ChickenSpawner : MonoBehaviour
{
public Chicken chickenPrefab;
public GameObject ground;
public void SpawnChicken()
{
Chicken newChicken = Instantiate(chickenPrefab, transform.position, Quaternion.identity);
newChicken.Initialize(ground);
}
}```
what u mean by that?
are you using UI components for all this?
if ur gonna set the position of the chicken/egg/ or whatever.. u can probably just leave it anchored to the center
dont quote me on that tho...
i tend to use 2D Sprite objects.. instead of UI components
which dont have an anchor
well you can but it would be part of the platform script and you can read it from the chicken. Or the platform could have a function where you pass in a prefab reference and it just spawns it for you within the area.
That's the issue I'm trying to solve. I have two game objects: one at the top left and one at the bottom right.
I also have an egg prefab, but I can't assign these two objects to it to determine the spawn area because prefabs can't take game objects
ALmost every programming problem can be solved by adding layers of abstraction or indirection
because prefabs can't take game objects
This isn't quite accurate. The rule is that assets cannot reference objects in the scene.
They can certainly reference other assets or objects within the same asset
well that problem has already been solved for u..
regardless of ur setup its the same problem.. u cant put scene references in a prefab
ya xd
u have to do that after the prefab is instantiated
thats true for every prefab.. not just Ui objects
u can use regular values for the bounds..
just find out what the X coord is for the left one.. and the right one
and what Y coord is for the top one and bottom one
True I guess, you could also do it that way
i guess its the easier way

bump
months and months of dealing with this issue
this is a code channel
Why does this hide cursor script not work if I add it as a the player component?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HideCursor : MonoBehaviour
{
void Start()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
did you click into the game view / is the game view focused??
Hello, could anyone help me im trying to figure how to make when Playerisdead the player couldn't move ?
Which part of this are you struggling with? This could be a simple if statement
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
this is my script https://gdl.space/usunaxipav.cpp
Think about which parts of this script you dont want to run if the player is dead. You can just return early to stop any logic from happening further in the function.
does anybody know what causes my player to act like this? (im referring to the slowly sinking on invisible floor and being unable to jump off the ground)
https://hastebin.com/share/veragiduco.csharp
heres my movement script if you wanted to see it
your controller probably is flagged as isGrounded when that starts to happen
its probably how u implement ur gravity
Yes I understand the issue, and my answer above is to guide you how you can return early from the functions that do move the player. Also you could just set the rb to kinematic, but then it will also not even fall on the ground
how do i return?
! means not
thanks
! does the opposite for bools, so !canMove means "if I cant move"
!canMove or cantMove would be the same thing
but thats just my example.. u can use a false flag or a positive flag
and name it anything u want
so if i am dead but my player can still move
if(!canMove)
{
return;
}
}
}
its weird though because it differs depending on the height i fall from, example:
so i put walk and thoose things in return?
if(dead){return;}
that way, if !dead.. the return wont run.. and the code below it executes.. (the movement code)
mhm
ya, because you've built up momentum on the long fall
What are the most common questions being asked in beginners code?
the code thats working against u when isGrounded.. isn't going to slow it down as much
why my code not work
how fix
Mmmm okay
its differnt day to day..
a lot of How i reference this
how i make this code do this to this other object..
or why i can't make my prefab do a thing (when they're trying to access the actual prefab and not the instance)
what does this mean
orrr.. how can i set this thing from this other scene before i even access the other scene
so honest π
I want that <incredibly googleable thing> to happen. Does anyone have a script I can use
oh oh, heres the best one: chatGPT told me to do this, and it was working at first, but i changed something and now it doesn't
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
how about 'I changed nothing and now it doesnt work'
i feel like i culd be perfectly fine with posting a screenshot of a codeblock and making them copy it out.. as an alternative of telling them no freebies
theres a problem here...
if you return early.. its skipping all the code beneath it..
meaning.. if ur bool isDead is true.. theres no possible way for the code thats highlighted to set it back to true
how do i fix that?
ohh wait.. that doesn't matter.. because its already true if thats the case
whast wrong with it?
i want the player to stop mowing
well when its dead it will..
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
when green is true the return makes it skip the rest
if its false.. it skips the return and does the rest of the code
Well yeah
public void SetWalking(bool _state)
{
if (isDead) // Check if the player is dead before playing the sound
{
return;
}```
look at what your code does
dam
it's not going to reach the part where it stops the audio source
it checks
i want like when the player is dead the sound would stop working because now when the player is mowing the realistic sound of walking starts playing
Something like
public void SetWalking(bool _state)
{
if (_state && !audioSource.isPlaying && !isDead)
{
// Play the walk sound
audioSource.PlayOneShot(walkSound, soundVolume);
}
else if (!_state)
{
// Stop the walk sound
audioSource.Stop();
}
}```
now it shows this menu but when i press w i still hear the sound of walkingπ€
Or perhaps just
public void SetWalking(bool _state)
{
if (_state && !audioSource.isPlaying && !isDead)
{
// Play the walk sound
audioSource.PlayOneShot(walkSound, soundVolume);
}
else
{
// Stop the walk sound
audioSource.Stop();
}
}```
but idk if this code is even running at all on the menu something is off
you should probably not even have the movement script enabled anymore when the player dies
Hi, it's my first time making a post in this server so sorry if something is posted incorrectly. I am making an FPS game as a project but have ran into an issue that I am having trouble fixing. I am making a hover system where upon hovering, the GameObject is outlined (using an Outline script that I got from the Asset Store called QuickOutline) and when F is pressed, the GameObject is also destroyed. I'm trying to hover over a stationary gun GameObject with a raycast and it doesn't detect it.
Couple of things I have already tried:
- assigning a Box Collider to both the GameObject and the model within it,
- assigning the Weapon script to the GameObject,
- tried using ChatGPT to add debugging logs and it said that the raycast detection was working perfectly but it wasn't detecting anything: No Weapon component found on hit object or its parent UnityEngine.Debug:Log (object) InteractionManager:Update () (at Assets/LowPolyFPSLite/Scripts/InteractionManager.cs:72)
https://hastebin.com/share/eyuqagizic.csharp <- InteractionManager
https://hastebin.com/share/kicozatemo.csharp <- Weapon
https://hastebin.com/share/nonusezoti.csharp <- WeaponManager
Apologies if this post is not formatted the best, thank you!
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Have you done any debugging?
I see you said you used CGPT to do it but...
You need to print which objecty your raycast his hitting
make sure you're hitting the expected object
note that it will be the actual collider object, so if that's a child of the gun, it's not going to have the other stuff directly for example
Debug.Log and print what you're hitting
I used ChatGPT because I've never debugged something manually haha, not experienced with that sadly. I'm doing this as part of my uni course. I'll try to debug it and post what the raycast hits.
well, it's time to get some experience (:
All you do is put print statements where you expect certain things and compare what it prints with your expectations. You're trying to deduce what's going on with the code
Debugging is such an underlooked skill
The version with debug logs: https://hastebin.com/share/idoyecaquy.csharp
The return is "No weapon detected by raycast.
UnityEngine.Debug:Log (object)
InteractionManager:Update () (at Assets/LowPolyFPSLite/Scripts/InteractionManager.cs:48)"
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
ok but you should log more info
Yeah I don't really know how lmao
Just print the name or something
for example
Debug.Log($"The name of the object we hit was {objectHitByRaycast.name}");```
but really... you are being pretty careless with some of this
There's a difference between hit.transform and hit.gameObject and hit.collider
those can be different objects
so.. start printing out what everything is
I was following a tutorial on YouTube for this because I'm not too experienced with Unity overall. I ran into this issue and just haven't really found any help with it online.
I debugged it the way you're detailing: https://hastebin.com/share/nenirohoqe.csharp
And it says that "Raycast hit: Box_01 (4)
UnityEngine.Debug:Log (object)
InteractionManager:Update () (at Assets/LowPolyFPSLite/Scripts/InteractionManager.cs:33)"
Box_01 is a box asset which the GameObject (the gun) is placed on so it seems like it's ignoring the GameObject completely.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
ok so we learned somethign!
Your raycast is hitting the gun itself
hello, why AI refuses to pathfind when i build my project, but it does well in editor
Can you teach me how like I'm five years old lmao, I'm new to Unity sorry
you can just use a layermask on the raycast.
Or perhaps rethink why your gun even has an active collider at this point in time in the first place
I tried a layermask earlier because that's something that ChatGPT recommended me actually but it's already set to the default layer
Yeah why
You need to use a mask that includes the interactable things but doesn't include other stuff like your gun
For this raycast we only want interactable stuff right?
Yeah so I want the guns to be detected by the raycast to be hovered so the outline script works when hovered or to be picked up with a certain key
but not other stuff like the boxes
the gun you're holding is certainly not something we want our raycast hitting
so either exclude it via a layermask, or turn its collider off entirely
It's not being held. It's placed down stationary
because again, why does the gun you're holding need a collider
oh it's not the one you're holding
The gun isn't being held by the player
ok but like
Oh it's a totally separate object
yeah
ok then yeah your gun either doesn't have a collider
or its collider is on a layer that's being ignored by your raycast
or your raycast isn't passing through it
I think it might be the raycast not passing through it. It detects the box but not the GameObject itself so I'm 100% certain that the raycast is working but the gun just isn't being detected for some reason
ok and the inspector for the box?
Wait I just noticed something, it said it hit Box_01 (4) but Box_01 (4) is over here.. the box under the gun is called Box_01 (8)
ok so probably your raycast is just going in the completely wrong place
Yeah most likely
Looks like you're using Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
Where's your main camera located?
MainCamera's located on the player body
Won't post the image for some reason
One second
You sure that's the main camera?
?_? How is it not
the main camera will have the MainCamera tag
Oh
so you are firing your raycast from some completely different place
I gave it the tag now
well...
Let me try again
now you have two
you should find the other camera that had the tag
wtf
(there could be more than one)
all the cameras that came with the asset I installed had the maincamera tag on all the cameras and there were like 5
lmfao that is not something I bothered to check
yep there's your problem
Let me test it out now
in the future a Debug.DrawRay with your raycast will also have revealed the issue
It would show that the ray is going in the completely wrong place
Oh my god it works
Amazing
Yeah thank you, I never thought about that
As I said I'm new to Unity, I spent over like two hours stressing about this and couldn't fix it haha
Thank you
Can you tell me which area of my code I could put this in?
I'd like to try it out before I get off
the spot where you do the raycast of course
"Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));"
Here then right
hello, why AI refuses to pathfind when i build my project, but it does well in editor
You should make a development build and see if you're getting errors
A console will appear in the game to display them.
Nevermind did it, thank you @wintry quarry. I appreciate it tenfold
RuntimeNavMeshBuilder: Source mesh Plane.011 does not allow read access. This will work in playmode in the editor but not in player
UnityEngine.AI.NavMeshBuilder:BuildNavMeshData
couple of bilion theese
"GetRemainingDistance" can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.StackTraceUtility:ExtractStackTrace ()
and coupple of bilion theese
thannks for help
So you're building a navmesh at runtime, then?
yes
if you're using the "Render Meshes" mode for NavMeshSurface, you'll need to enable Read/Write on the relevant mesh assets
thank you
Hello I have a question,
I have 3 scenes in my game, when I load a scene after the one prior is complete it just shows it without actually running the game or initiatializing anything, any recommendations?
I used SceneManagement.LoadScene
wdym without actually running it? what happens
It = next scene
show your code
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
It actually loads it but just shows it on game view without anything running
For more details these scenes are a copy I created (ctrl+d) with some changed varriables
how do you know that nothing is running? do you have components with Awake/Start methods that aren't running?
(you'd add a log message to check this)
Hello, i am having an error from assets ive imported.
I was wondering if someone would be able to assist me in finding out whats causing it and how to fix it?
Well its telling you the script, the variable, and where in the code the error is coming from.
That type of message means you need to specify Which place to use the MinAttribute from (in my limited knowledge)
Specifically, you have two namespaces that use MinAttribute and you need to specify which one you're using.
You can first see if you're even using both the ones specified by checking at the top of your script in the using. If it's greyed out, you can just delete it.
hi im fairly new to unity and im recreating watermelon game, does anyone know how to make it so the cloned fruits are deleted when the game over screen pops up?
No a List
Java has lists too BTW
Unless you're talking about ArrayList
C#'s List is the same as Java's ArrayList basically
oh ok ill check that out tyy
Guys another quick question sorry, I have different levels (scenes) in my game. I want to set a var differently for each level through serialized field. The problem is it sets it the same for all levels I canβt have different values for it
Where does the field live?
On a script? Which script?
Yes on a script this script is responsible for animation. Basically called GermAnimation
It is attached to a prefab
Ok and you are instantiating it into the scene at runtime?
The var is an int for germ magnitude responsible for the max magnitude of a germ so not during run time
Then you need to either put the prefab directly in the scene at edit time instead and edit the value there, or use another script which you put in the scene and set the field there, and have it communicate with the germ one
If it's not at runtime you can just set it differently in each scene
On the actual instance in the scene
It changes
Like if I set it one it is the same for all the others
Only if you are changing the actual prefab
But the one in the scene can have an override
I need help someone please. I don't know why i'm getting errors for this, but I may just be stupid
First thing's first you need to configure your IDE
When it's configured you will see your errors underlined in red in the code editor itself
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
thanks!
you will also get autocomplete etc
Good evening everyone
I am currently having an issue where I'm trying to split the player and launch it towards the mouse cursor
However the issue is that it doesn't seem to want to go towards the mouse and I can't seem to quite understand
Can anyione tell me if there are any issues with my code?
void Split()
{
if (transform.localScale.x <= originalSize * splitFraction)
{
Debug.Log("Player too small to split");
return;
}
// Reduce player's size by a tenth before splitting
float newSize = transform.localScale.x * (1 - splitFraction);
transform.localScale = new Vector3(newSize, newSize, 1f);
// Create the detached part
GameObject detachedPart = Instantiate(playerPartPrefab, transform.position, transform.rotation);
float detachedPartSize = newSize * splitFraction;
detachedPart.transform.localScale = new Vector3(detachedPartSize, detachedPartSize, 1f);
// Launch the detached part towards the mouse cursor
Rigidbody2D rb = detachedPart.GetComponent<Rigidbody2D>();
if (rb != null)
{
//find mouse position
Vector3 mousePos = Input.mousePosition;
mousePos.z = Camera.main.nearClipPlane;
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(mousePos);
//Sending it towards the mouse
Vector2 launchDirection = (mousePosition - transform.position).normalized;
rb.velocity = launchDirection * launchDistanceMultiplier * detachedPartSize * launchVelocity;
}
// Set the cooldown timer
cooldownTimer = cooldownDuration;
}```
what does it do instead?
I think its shooting opposite of the mouse actually when I take a closer look
Have you tried using Debug.Log here to print out the various values involved in your velocity calculation and the resulting velocity to see what's going on?
specifically all the stuff here:
rb.velocity = launchDirection * launchDistanceMultiplier * detachedPartSize * launchVelocity;
This seems maybe a little sketchy too: mousePos.z = Camera.main.nearClipPlane; You sure that's right? And is this an orthographic camera, or a perspective camera?
Camera.main.nearClipPlane is almost definitely really small
With a perspective camera it's usually better to use Plane.Raycast instead
is there any particular reason?
Yes because it lets you actually get the world position on the desired plane in the world you want
instead of hoping and praying like you do with ScreenToWorldPoint
with ScreenToWorldPoint you need to make sure the z distance is correct, and correlates to the plane in the world you're interested in
And see the bottom section about using Plane.Raycast instead which is better IMO
Almost always in these circumstances it makes more sense to specify a plane on which you want to project the mouse, rather than a distance
How did you make your object face the mouse? I have been trying to do that for a while
2d or 3d?
3d
You do what we're discussing here to get a world space position
then you do myObject.transform.LookAt(mousePosition);
or you do transform.forward = directionTowardsTheMouse; which you'd calculate based on the mouse world space position
or transform.rotation = Quaternion.LookRotation(direction, desiredUp;
lots of options
im searching how to measure the distance between 2 points, found vector2.distance but i cant manage to make it work, i need to know the distance in a line from point a to b in meters in both x and y dimensions, but every video that i find displays it only in the x dimension
I just tried that and its rotating in multiple directions as well as not rotating a full 360
Vector2.Distance does it
it's literally the pythagorean theorem btw
yes i know
It gets the raw straight line distance between two points
So what's the issue with it?
and that straight line should be 1 single number that would be a float right?
i try to make a comparison with an if and it tells me that i cant do that
show exactly the code you wrote
omw
and the error you got
sounds like you tried to compare a Vector2 with a float or something
Yes, that's what it returns
What the hell is new Vector2Distance
Why did you write new Vector2Distance?
What is that
distance = Vector2.Distance(a, b);
yes
which is just.... nonsense to be frank
Which would be a class named Vector2Distance, which you would have had to create
whenever i create a var that is a vector i usually need to create a new vector to which i can later on make the var that i created compare or make equal to
I think you have a fundamental misunderstanding how variables and values and expressions in C# work
remember, first of all, that you're not creating a Vector2 here
you already have two vectors
and you're trying to create a float that is the distance between them
and we have a function that does that
so no need to construct anything with new
yes as soon as i read that i realized that i should change the var to float
im an ape bruh
i even looked at the docs and found nothing but 1 line and got scared
lmao
but it was a whole diff thing
ty guys!
What do you mean world position
The mouse's x and y?
the position of the mouse after converting the screen space coordinates to world space
does OnCollisionEnter not get triggered if the rigidbody it is colliding with is kinematic?
I have a wall
OnCollisionEnter needs at least one dynamic body
I dont understand how you would convert the two
that was the whole subject of the conversation above #π»βcode-beginner message
Yeah ive read that like twice now
well I'm not sure how to help much further than that
You clearly didn't read this then https://unity.huh.how/screentoworldpoint
are there any other ways to detect collision with zero rigid bodies
π©
is there a reason you need to not use Rigidbodies:?
maybe explain what your goal is
ok so
I made a monster neck by making a bunch of spheres follow eachother
and the problem is
the neck goes through walls
so I want to use collision detection to make it not go through walls
but adding a rigidbody breaks the way the neck works
well you either need to re-make it with dynamic Rigidbodies or you need to do your own Sphere/Circlecasting as you move the pieces of the neck to make sure they won't go inside stuff
Hence what I said about "direct physics queries"
The problem with "remaking it" is I cant figure out why rigid bodies break it in the first place
Seems pretty obvious
Huh?
adding a realistic physics simulation fights with whatever your existing movement logic is
Ok but I can just choose to disable gravity
even doing so it still has issues
My code is literally just a bunch of distance checks
so if sphere1 is too far from sphere2 it moves back
gravity is only one aspect of the physics simulation
simply disabling gravity doesn't take away from the fact that the physics simulation is fighting your code
your code is attempting to directly control the spheres.
The physics engine does the same thing.
Chaos ensues
you either need to work with it or bypass it.
hence my suggestion here
Hello, in my code, I have .SetActive(false) for the child game object, is there a way to activate back the child object by activating its parent object?
no, you will need to directly activate the child now
ok thanks
if this is a problem you're encountering, do you happen to use transform.GetChild?
or anything relating to getting/finding gameobjects
Thank you, i used the plane and raycast however my object rotates in multiple axis when i only want it to rotate on the y axis
using these isn't very healthy
I cant seem to figure out a solution
that means you used the wrong plane
if you use a plane that is at the height with your object on the y axis, it will only rotate on the y axis
very simple to do that if you just use your object's position to build the plane
I tried using my objects position but it doesnt work
it works
maybe show your code
and your scene setup
and what you're trying to do
guys i have spaghetti code π©
How does movePosition differe from MoveTowards
MoveTowards is just a math function, it just calculates a position.
Rigidbody.MovePosition is teleportation with RIgidbodies that respects the interpolation settings
so then the commented out line and the three lines below it are functionally the same right?
(because they are absolutely not working the same in engine)
except for the * 1.15 bit
but also
it depends where this is running
if it's in FixedUpdate yes
if it's in Update then you're doing it wrong
because Rigidbody.MovePosition only can live in FixedUpdate
Ah
woops
And a third point - MovePosition doesn't really help you here
it doesn't respect collisions
Well you said I need to change the way to neck works to use dynamic Rigidbodies
and after that I can worry about collision
I said that was one option
and if you're doing that you'd have to deal with velocities or forces
i remember doing this in my last project but i cant find anything that i manage to understand, how was it that i rotated something in the z axis at the moment of instantiating it ?
can i check if a list contains a specific field on an element?
wdym by containing a specific field on an element?
You mean if any element of the list has a specific value for one of its fields?
so my list contains items that are scriptable objects and it's checking if it contains a specific item/s within it
bool containsItem = myList.Contains(someItem)
this
Either write a loop and check each element, or use Linq.
Im on mobile, would a picture be fine
alright
would prefer !code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Yes i would do that but the internet on my pc is broken
ive got a countdown script, but it starts when the game starts. is there a way to hide it and then have it appear and start at a certain point in the game?
disable it
no like the enabled checkbox
this one?
that works yes
or just disable the script itself
activate it
how do you activate it in code
You're trying to call SetActive on something other than a GameObject reference
ohhh rn im calling it on the script
does it work on a textmp?
ohh ok got it
all of these things are components that are attached to GameObjects
THere's no way to have a TMP that is not attached to a GameObject
so I don't really understand the question
those are GameObjects
at a certain point
Everything you see in the Hierarchy is a GameObject
TMP_Text is a COMPONENT
do you understand the difference between Components and GameObjects?
everything in the hierarchy is a GameObject.
GameObjects have components attached to them
When you select a GameObjectyou can see all its Components in the inspector.
these are components^


