#💻┃code-beginner
1 messages · Page 25 of 1
So i have a little spider that i'm trying to animate procedurally. But when it starts moving, the little targets are getting huge a offset on the Z axis. The spider still walks, but with the legs in this position.
I think its coming from the line 75 of this script : https://gdl.space/nogagabiki.cs
Because when i try to remove the offset, it aligns way better. But still not good because its adjusted manually
If anyone has an idea, or tips. Its a code i tried to reproduce from a work online but ended up copy pasting it coz of this bug i thought was coming from my version.
Look into platform effector
https://docs.unity3d.com/Manual/class-PlatformEffector2D.html
not sure about the second part of your question, I'd assume something you can find easily on google/youtube
I fixed it thanks
dont crosspost
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
I would use a debugger with a breakpoint on line 75 to see the values going in
hello i'm wondering why this entity is not moving at all
Enemy enemy = collision.GetComponent<Enemy>();
if (enemy != null) {
Vector3 parentPosition = gameObject.GetComponentInParent<Transform>().position;
Vector2 direction = (Vector2) (collision.transform.position -parentPosition).normalized;
Vector2 knockbackApplied = direction * knockbackForce;
enemy.Health -= Damage;
print(knockbackApplied);
enemy.KnockBack(knockbackApplied);
}
public void KnockBack(Vector2 Force) {
rb.AddForce(Force);
print("AppliedForce");
}
how do you move it normally?
i have no clue what u are asking
how do you normally move the enemy
he doesn't move
there no movement as of now
i only have knockback
and it doesn't work
either you've made your rigidbody kinematic or you are doing something else that is affecting its position
i have kinematic
kinematic rigidbodies are not affected by forces
i just see the values as they are
like
ahh i see
it just goes from normal value to 8
on the X axis sorry
i mean to that offset
idk what i'm supposed to get from that debug, i know that this line fucks up my coordonates
i'll try things tho ty
To see where the offset is coming from. Show the values when it hits the breakpoint
Hi. So my player does a little jitter? As seen in the video. I'm aware of why it's happening. The Player moves faster than the camera and my player rotates to the mouse for a split millisecond then centres again. I've got it so while I'm dashing, my player cannot aim, move or shoot. Not sure how to do a work around.
I'm a little unsure of what this code does and I wanted to ask here to see if I understand it correctly. As I understand it this code is making it so that the transform's rotation and the camera transform's rotation are are being linked with a delay of .2 seconds.
{
transform.rotation = Quaternion.Lerp(transform.rotation,Camera.main.transform.rotation,.2f);```
no that .2 is not seconds
its called Interpolation ratio
interpolation is one value to another , the ratio is the values between
its how much it takes from the second value and how much it doesn't take from the first
say you had .5f
your rotation would be a combination of half the rotation of each
oh
so if its .2 then is the transform rotating at a rate of .2 as opposed to the camera's .8?
meaning its at 20% the rotation of your Cam's rotation
if you want a smooth transition from one to another you have to increment the value with some timer
yeah i kinda suck at maths
maybe there are some videos that makes it simple
Your thinking of it as a rate.
If you have an unchanging value in the third parameter, nothing will change
It will just stay the same place
i can give you another exemple if you want
sure
If you have values of 0 to 10, and your third parameter is 3, you will just get a 3
does it mean that the object rotates 80% slower than the cam?
Faster and slower doesn't really make sense here. If it doesn't increase, it won't rotate at all
i understand the 0 to 1 part, just not really how it affects the transform and camera rotations
forget that part. Your lerping between 2 values regardless
imagine those color tapes, one side if full blue and the other side full red
colors in between are obtained by interpolation
You are setting the rotation to a different thing each frame. One frame it will be this EXACT position, the next it will be a different one.
like in the middle its 0.5f bc its 0.5 of blue and 0.5 of red
yeah
transform rotation change each frame
so it rotates
@muted wadi another visual example with rotations (timestamped)
https://youtu.be/1yoFjjJRnLY?t=417
its using SLERP but same concept applies
In this 10 mins GameDev tips we are going to explore Quaternions in an intuitive way. Don't expect deep math derivations. However after watching this video you should have a good mental picture on how they could help you dealing with rotations and orientations in your game projects. I will start by describing euler angles and their issues follow...
question about farming implementation. So I have functionality that you can plow soil, plant a seed and that seed will grow/be harvestable. I currently use SetTile to change the tile from a plow tile to a seed tile. Is there a way to change the image of that specific tile without using the .SetTile method? Is it using some sort of the .SetAnimationFrame method for the tile? then I just have it show a certain animation frame compared to where it is in the growth cycle
ok i think i get it
so its setting the transforms rotation to be 20% cam and 80% original
basically the position between those two
rotation*
to rotate smoothly
Lerp? like a billion types of use
what's that
is that like a transition between one type of thing to another?
oh ok
can be used for that
i see
man, whoever told me that maths wasn't very big of a component in coding lied to my face
there is so much math
even more math in games lol
in games only tho
IA too nvm
and image synthetising too nvm
i noticed that when trying to figure out how to code a camera that doesn't go through walls
go WEB if u dont want maths ig ... x)
nah i wont give up just cause of something like this, i wanna make something special in the end
Game Engines help though because they specifically have math functions so you dont have to sit there manually write formulas
so as long as you know the concept behind something, the code is second
esp important Vector math, Trig etc.
that's true, but understanding the functions and how they can be applied is still pretty hard
Could anyone help me please. I would appreciate it a lot
Rotations being the worst imo
whats an easier or cleaner way to format an integer from 1-3 digits to exclusively be 3 digits ( example, 3 becomes 003, 27 becomes 027 and any 3 digit number is preserved ) without using yucky looking if statements
formatted into a string ofc
First, try moving your ProcessInputs() call into update. Not FixedUpdate
Leave Move() where it is though
I had it like that before. Still the same
double checked now too. Still the same
Yeah, I wasn't too hopeful that would do it. BUT you should always capture input in Update. You'll get issues doing it in FixedUpdate
Now, I'm not sure I see what you mean by jitter in that video.
Yeah my way stunk. lol
I kept doing ToString("00") to ToString("000") untill I seen that letter
wh
Show your code
right ig i gotta add more brackets bc it originally yelled at me for tryna make it an int
Would you use N?
Or you can use the 000 format
when i dash. my player snaps to the mouse then centres and it looks like it glitches? I dont know how to describe it. It's very noticeable ingame and makes the dash annoying
Ah
D3 seems to work fine when I cast to an integer
Yes, D only works with integral types
this will vastly simplify a lot of my code bc for some reason im obsessed with formatting numbers that way lol
The link I posted has a neat table (scroll down) that shows what's supported by which types
for some reason I also stylize :s into //s
I see two solutions, disable aiming during the dash, or have the camera move more precisely with the player. I dunno what else to do about it at the moment. But I'll keep thinking about it
Edit: i dunno if the first would help, but my thought is that it would reenable when the camera is back in position
I wonder how similar it is for java bc I missed the day I was supposed to learn the exponent formatting for college lol
but yeah thanks, v helpful :3
I did think that. Maybe extend the disabled rotation for 0.1 seconds or something? I just don't know how to implement that into the script
This is it slow motion.
@silent valley Ok yeah I see that more now hmm.
And looking at your code more, you DO disable aiming while dashing 🤦♂️. Sorry, should have looked closer.
I'm thinking the mousePosition needs to be guaranteed to update before the rotation, because it's trying to use the LAST position.
So what if you allow ProcessInput even when dashing, and ONLY block Move?
Or make a ProcessAim function and allow only that
I've also tried this. No luck. It's annoying cause I can see what the issue is. Just can't find any solutions.
Hi there people, one question to anyone who might know about this, i have an issue were my character goes trough my tilemap collider 2d and the tutorial i am following says to enable "used by composite" option in the component but i can't find it anywhere, i have 2023.1.13f version, perhaps anyone has sorted this out with this newest version?
@silent valley The only other thing I can think is to make the rotation smoothed, using lerp or movetowards, but that would affect normal play too.
Can I just not disable the movement for a few miliseconds longer than the dash duration?
I also used cinemachines virtual camera just to see if it was my camera script. it wasnt.
You should definitely try it. I'm not sure if it will work.
It feels like for a single frame it's trying to look back at the last position? Maybe you could also save the rotation when you start dashing and set it to that first thing coming out? That would give it a single extra frame to sort things out.
Sorry, I am so bad at rotations haha. I'm just throwing stuff out there
I'm new to 2D games. Do you know how I'd save the rotation?
Also I appreciate any help. i'm so close to having a mini demo release. just little bits to fix
Just something like Quaternion oldRotation = transform.rotation? Not sure
Would you mind giving me a little hand with that please?
Guys, how can I clamp my x rotation?
Store the rotation in degrees as a variable in the class
Add values to that variable. Clamp and apply whenever needed
Did this on my phone, so might be errors haha
But just something like this
https://hatebin.com/kuasrndiik
I only modified Dash()
I have no idea if it will help or make things worse lol
rigidbody2D only rotates on Z axis so its a float
what do you mean by it's a float?
It's a single number
that can have decimals
In Rigidbody2D: public float rotation;
I know what a float is. I meant I didnt quite understand the reply. If I'm right. does it mean since it only rotates on the Z, it can only ever be 1 number (0,360) plus the decimals?
Correct
makes sense
Since in 2D rotating around X/Y would produce unwanted results (object might be invisible or backwards), they agreed upon using a single float, the rotation around Z
How would I make a system for it to auto set your height and correctly adjust for arm length. I’m new to this.
but how?
class Sample {
private float rot;
void Update() {
rot = // something
rot = Mathf.Clamp(rot, min, max);
transform.rotation = Quaternion.Euler(rot, 0, 0);
}
}
like this?
Like my code
Values you get from transform.rotation are not in degrees and cannot be used as angles
Quaternions are complex objects that represent rotation on 4 axes, XYZW
Each value ranges from -1 to 1 (float), and represent one rotation component
^^ On this point, if you're confused when you look at the inspector its big numbers, you're seeing Euler angles
What you can do though is still use the variable like my code, but accumulate the quaternions, if you need to keep the Y/Z values in degrees.
transform.rotation *= Quaternion.Euler(rot, 0, 0);
// ^~ NOTICE MULTIPLICATION ASSIGNMENT
Multiplying two Quaternions adds the second one to the first
We are all talking about rotations. Does any of this apply to what I'm looking for? 😅
what I don't understand is what should I assign the rot variable to? Because for me to rotate my player I'm using Transform.Rotate()
You can't use transform.Rotate if you want to clamp
You need to deal with the clamping, which means you need to assign the rotation after the clamp operation
This is def not a coding question, but I can't seem to find the right channel for this ype of question. Unity store's add asset is not working for like literally one asset that is perfect for my needs. Is the a way to reset the store or something similar?
ooh, so this is the line that will replace the transform.Rotate()?
I'm also experiencing the same issue. I have to go Windows/package manager to add what I get of the store
Like in files?
Yes, but you will need to apply the movement over time yourself on the variable directly.
Usually done with two variables. One is the target (final rotation), and the other the current rotation. Move the current towards the target, and clamp it before assigning it to rotation
With this, you don't need to use *= anymore for the quaternions
in unity you have a windows dropdown. there, you will find "Package manager" . Your asset you added from the store will be there
prob not :x
but if you wanna see a cool gif showing what unity does behind the scenes with quaternions here
you may need to change the dropdown within the package manager to be "My Assets"
so the W number is a unique number for every possible rotation?
Yeah, I figured out how to get the assets from my assets, the actual issue is being able to add things from unity store to my assets...
https://en.wikipedia.org/wiki/Quaternion
I decline all responsibilty for any brain damage reading this article may induce
In mathematics, the quaternion number system extends the complex numbers. Quaternions were first described by the Irish mathematician William Rowan Hamilton in 1843 and applied to mechanics in three-dimensional space. Hamilton defined a quaternion as the quotient of two directed lines in a three-dimensional space, or, equivalently, as the quotie...
lmao even the image is confusing
I'm kinda glad I ran into this problem. i feel like I've learnt so much tonight xD
5D chess brain is needed
if your account is linked. it should auto add when you add it on the store
but yeah w is just another axis
fml. All this cause I wanted a cool dash xD
so the direction is not working or what?
you're doing 2D you should not be worrying about quaternions
just trig lol
Yep! Unfortunately someone needs to tell unity that... I can add literally any other asset but this one
direction is fine. just the little aim thingy it does.
why are you disabling rotation during ?
I kind of noticed that once it got mentioned about being a float and reading online about 2d rotations
yes gotta think in radians
just a preference. I could do it without disabling it. but the dash doesnt look smooth
i have it so it isnt disabled right now but ideally would like to learn why it does that and how to fix instead of avoiding the hard stuff
so its solved ?
it is if I don't disable the rotation. (was just a preference because the dashing looks better when rotation locked)
Also thank you for teaching me new things. I'll be studying this over the next few days
is there a max size for custom generated meshes with code
for some reason when i try to make mine greater than 200x200 quads it gets weird
65k or so
ok thanks
it will probably be better to make multiple anyways so i can implement chunks at some point
transform.position = waypoints[waypointIndex].transform.position; this line in Start teleports ur balloon to the start
anyone know how to check ints without using Update? I'm making a clicker game and once you reach 100 clicks, a win screen appears. Due to the fact that I put my checkers in update, it constantly repeats setting the win screen active instead of doing what it's supposed to be doing. which is restarting the game. I'm not going to restart the scene because I have a private int running in the background to check how many times the player has beat the game. Here's the code: https://paste.ofcode.org/ThYyawh6F3DeadHK7NhhPq
You can just add a bool called won
Then do
if (score >= 100 && !won)
Then when you win, set won to true
It will no longer repeatedly set the win screen active
OTHERWISE you can turn score into a property, and in the setter you would invoke an event or call a method when score is 100
I don't think I'm doing it properly
Should there be a default state to the bool?
it's in the update method
Got it? Sorry, I stepped out and missed the question. Good working getting it done though!
you've got to be the most kind person on this server. every time I ask for help on here, they always do that stupid !ide command
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Having a configured IDE is required to ask for help here.
I have
i've had it configured for about a year
but, now I've got it done
so thanks guys
I will say, that IS one of the most helpful things we can do. An configured ide is crucial for proper coding. If I had seen your ide was unconfigured, I would have done it too 😂
yea and then ur ide will come up with this https://hatebin.com/hwdjpmbwtj wtf is that python ahh code bruh
dont even trust it being equivalent code
if i do chunking should i make all the chunks be separate game objects?
You don't have to follow suggestions made by an IDE. Also, I've never encountered my IDE ever suggesting verbose Linq like that
How do I convert the rect transform of a text and a transform of a game object? This is a 2d game and simply assigning a rect transform to something's transform doesn't really line it up
You are talking about transforms. I think you actually mean positions
yea ik u might be turned that off cause ive got default settings 
The conversion between a rect transform and world space depends on the canvas render type
My canvas type is world space with posx and posy being 0,0 and it has a child with a transform the same as an object in the scene + a child that is text
i've been doing trial and error but I can't seem to make those positions equal
If you just need text to exist in world space, you should use a world-space TextMeshPro instead of a canvas
oh that's better actually
it's what I set when the engine's in play mode lol
at least its noticeable i guess
yea
with these noise setting how would i make it look like small hills but then have big mountains in some places, if possible
ive been messing with them for a while and cant get it
how to add something in these options? for when i want to instantly add a prefab i frequently use
With MenuItem
You put menu under GameObject/ iirc
thanks imma try
External Dependency Manager is unable to resolve successfully on my new computer, is there anything I have to setup for it to resolve?
is this an android project?
Yes, Android Resolver > Force Resolve is failing at 0%.
Are there a list somewhere of unity methods that can be and can't be called in async?
I think async runs on main thread so any methods can be called in async
Yeah. And if talking about multithreading, you should assume that none of the API should be used aside from the one that unity specifically uses in jobs system.
Some static utility methods might work on a different thread, but I don't think there's a list of them and you should consider all of the API as not thread safe.
I'm VERY new to Unity and trying to wrap my head around creating an inventory system.
There may be several GameObjects (Player, Store, ...) that have an inventory, so it needs to be re-usable.
How would I set up this Inventory (let's ignore items for now)
Should it be a ScriptableObject? Or just a Prefab? Or?
My game is gonna have a LOT of items with lots of attributes, if that is important
Well depending on what you want an Inventory can be as simple as List<Item>
Now if you want grid based inventory space management things get a bit more complex
I would default to the Unity way of storing state in Monobehaviours unless you see some issue with that in your game. Important part of reusability of inventory here is to keep all the things you might do with an inventory in their own monobehaviours.
See this is exactly my problem, I don't know and I don't understand any of that
I've followed this really long YT tutorial on how to make an inventory
It had UI controllers, ItemSO, InventorySO, ItemController, ...
It used a Dictionary and a List something something in different locations
And while it ended up working, I do not understand how it works
So I just wanna set up something simple right now, that I can later expand to my own needs
Keep your items in a Inventory Monobehaviour. Have classes like Player and Shop to implement class specific features related to the inventory.
I would consider creating your first item system for a simpler game to explore the basics of item system design if your current project has very complex item requirements.
I'm trying to get movement for 2d, ive got an action of type value with control type vector2 and an up/down/left/right composite thats digitally normalized.
When I try to run it, i can only move horizontally or vertically, not diagonally. i printed the ctx.ReadValue but it only prints [1,0], [-1,0], [0,1], or [0,-1]
how do i get it to output smth like [0.7,0.7]?
some code likes: direction=new vec2(getxasix,getyaxis);
idk if you are using new input system, i dont know how to do it
yea im using the new input system
found this but ive already done the solution
https://discussions.unity.com/t/new-input-system-isnt-letting-me-do-diagonal-movement-with-wasd-arrow-keys/240614
I started switching my inputs to use the Input System. Everything seemed to be working well until I started switching the moving code. I’m using the “Move/WASD” action from the default player action map. My issue is that it doesn’t seem to read diagonal movement. Left/Right doesn’t mix with Up/Down on either WASD or the arrow keys. The Vector2 v...
im just starting out coding with unity and i was wondering if dotnet was still supported?
dotnet in various formats is the only thing supported
ok thank you im new to this and have been trying for an ungodly amount oof time so i thought i would just check thanks for confirming
i cant remember the official name but the code support
comes up with the list of things u can use
ive been using just visual studio
so i want to try actually making smth playable
in the VS Installer there are 2 things you need, C# support and the Unity extension.
see !ide for more info
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
yes, both the extensions are provided by Microsoft - C# and Unity
I also use GitLens extension - only the trial version
Hi! May I ask if it's possible to add [animator] component to items in a list?
My characters are being spawned from a list to a prefab, I want to give each customer an angry reaction and given them a walk cycle, how should I go about this?
Hi. I am having issues with the new VS Code Unity support. When I open VS Code through a script in Unity it always opens a "clean" window with only that one script open. It doesn't remember what scripts I had open last time I used it.
I am pretty sure I have everything setup correctly on the latest versions. When VS Code opens it takes a minute to load the project and the references. Then it works for a little while I can Ctrl+Click classes and methods to see where they get used. When I type I get intellisense with proper methods avaiable etc. But after I change anything in the code and save it, it completely falls apart, Ctrl+Click ends up in loading something indefinitely and I have to close it, let Unity compile scripts and open VS Code again for it to work again. I think same thing happens when Unity is doing something like baking asset bundles or building where the intellisense,etc. stops working.
Is there a way to fix it or find where the problem is?
It would also be nice if the visual studio support package supported forks of VS Code. I was trying to use it with the Cursor editor and only got it to work with some workarounds that break after updating because the package has hardcoded VS and VSCode paths in it.
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
https://hatebin.com/icblqngqsr Any idea why my rotator coroutine does not work? I can rotate multiple times on trigger. I want to be able to lock it for .4 seconds.
you even didnt use the canRotate bool....you just set it
what are you trying to achieve?
There are triggers on my scene. When entered my character just turns on the desired axis. If i dont limit the turning, character can rotate 180 degrees or more, which makes it face backwards.
I wanted to use a coroutine to limit the rotation event
It works fine now.

can someone help
Instantiate doesn't take an array as a parameter.
I just started a new 2d project
I have a Character with walk animation, but it doesn't actually move
I also set up a parallax background (auto infinite scroll)
Now when my character gets into combat, I pause the walk animation, but how do I link my background object to this process? So I can also stop the background scroll
I could just add a variable in my character or combat script for the background, but that doesn't really make sense?
maybe you can make a bool in the movement script to turn on while moving
or something
yeah that's not the issue, the problem is I don't know how to link my character & background objects in a proper way
I'm just trying to add this to list to my scene - why can't I add it?
yea i have no clue im new too
looks like you're missing a "_"
I'm trying to add trees to my terrain but the below code doesn't work. Any ideas?
public static Terrain terrain; // Reference to the Terrain component
public static GameObject treePrefab; // The prefab of the tree or vegetation you want to add
public static void AddTrees(Terrains terr)
{
terrain = terr.Terrain; // The terrains terrain
treePrefab = Resources.Load<GameObject>("Tree9_2");
TreeInstance treeInstance = new TreeInstance();
treeInstance.position = new Vector3(Random.value, 0, Random.value);
treeInstance.prototypeIndex = 0; // Assuming the first tree prototype
terrain.AddTreeInstance(treeInstance);
terrain.Flush();
}```
looks like you're missing a "_"
Where am I missing this?
your class name is AngryCommentList instead of AngryComments_List like in the error
I tried removing the -
still doesn't work
this script is identical to my other lists - I just copied and paste it in, change the names for another list, so I don't understand why it's not working.
Comments =/= comment
?
The script name is AngryCommentList, not AngryCommentsList. So your script name needs to be AngryCommentList before you can add it.
I think
The file name and class name have to match. Do they?
Hmm
My previous scripts didn;t hv the problem despite of the naming conventions being different tho
They did, because it wouldn't work otherwise.
File name and class name must match in naming, not in casing
Huh?
I don't think this was a casing issue?
#💻┃code-beginner message
Just match your class and script names and be done with it.
Because comment is singular in the class name and plural in the file name
This script works perfectly fine
It's not supposed to work and it's a bad habit to do this in general, that's all I can say
If you say so. Not going to argue about it.
Unity assumes you have a single MonoBehaviour in a file, and the names match
I've sent so many SS showing that I matched it
it's still not working, im not arguing w you
All the ones you've sent don't match. 🤷♂️
Dude ^
The rest of the error states making sure you have no compiler errors. What does your Unity console show?
Right, then you have compiler errors
Until you fixed the errors, unity is not updating the context it was previously aware of and keeping that error
Can anyone tell me like whats the point of creating an interface when i have a complete scripte that control the Health logic
The point of interfaces is defining a "contract", or basically defining functionalities that a class must implement to satisfy this contract
So your enemy must be damageable, you make it implement IDamageable, which contains a contract that tells the class to have health, and a way to apply damage
Then when you have your level, and you shoot an enemy, the script checks if the enemy implements IDamageable, after which you can call that damage method
And this way you can have it implement many interfaces that define the context of a class
but in interface every property is public then anyone can acess the health property isnt bad i mean anyone can change it
You can restrict the get and set parameter if that's an issue. Otherwise don't add it I guess? Although I don't see why you would restrict people from accessing it.
Quaternion quartRotation =Quaternion.LookRotation(targetRot);
cj.targetRotation = quartRotation * startRot;```
would this work where cj is a configurable joint?
i tried but its not allowing that
if your code is working without an interface, why are you trying to add an interface?
public int Health { get; } means you can only read it
interfaces are pretty hard to understand and only useful in large projects
If you implement this, you can define public int Health { get; private set; } in the class
This way, you can set it inside the class.
Ahh ok that worked, thank you 🙏
No problem, my bad for not properly reading what the issue was lol
Might you also know the solution to this?
like i have health class and player class and health class has maxhealth varible first i have to set the interface health property equal to maxHealth and then i can use health why not create health varible in health class
I want to understand why we need interfaces are they faster than accessing other script
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
You don't need interfaces
All they do is expand your class and give you the ability to define custom implementation
So an IHealth interface can behave differently on two different classes
While being able to get in the same way
The point is that there will be classes that define the same functionality, as I just mentioned. The interface will define the similarity of these classes and what must be implemented to allow for the same functionality. It sounds completely pointless in what you're making and you should use them if you want to access different classes for the same purpose.
Let's say one class uses defence (enemy) while other doesn't (barrel). You can then implement different DoDamage() methods if it's a part of the IHealth interface
Yeah, so basically what I already explained #💻┃code-beginner message
Whatever is the case, basically custom behaviour for each class
Thanx i got it
Quaternion quartRotation =Quaternion.LookRotation(targetRot);
cj.targetRotation = quartRotation * startRot;
would this work? i am trying to set the target rotation of a configurable joint to point to the position of a raycast from a camera
https://gdl.space/oleyequgun.cs
just consider this script only contain 3 varibles
int maxHealth;
int health;
[SerializeField] Image healthbar;
i want to convert it to interface
Health class will only contain healthbar and i impliment other stuff on interface will it be faster than health Class or not
i mean i still have to send data to health class to change the health bar
I mean, in my opinion there are multiple things wrong with this.
First of all, I assume various actors in your scene have health. What you should do is define a class for these actors, and have them abstract from a base class that contains this health. You need an abstract class, and not an interface, because there's a base implementation when it comes to health.
Second of all, you should not merge your UI and the actual behaviour in one. You should have a manager, preferably singleton, which manages your UI. This will display the health bar, and not this. If you contain it all in one class it's much harder to manage and will most likely cause bugs.
What exactly is going to have health in your game?
enemys and player hp
and what is less cost effective directly assign a refrence from inspector or throught considring you are creating a large number of enemys
[SerializeField] HealthbarUI hp;
If you want my two cents, make a class Pawn or something that implements this, then have a PlayerPawn and Enemypawn inherit from this. PlayerPawn has all the input implementations, while EnemyPawn has all the NPC behaviour it needs. Pawn implements the shared context, such as health, height, mass, whatever you need
You don't need an interface for this
Is this a health bar above the enemy and player?
I would advice you make a manager still, but instead of provides this UI to display above the enemy. This way you only assign it once and the enemy can fetch the bar to display on top. Pawn will implement showing this health bar.
sorry my internet is not working correctly
what is less cost effective directly assign a reffrence from inspector or throught considring you are creating a large number of enemys
[SerializeField] HealthbarUI hp;
or
HealthbarUI hp;
hp=GetComponent<HealthBarUI>();
ok I'm confused:
{
[SerializeField] private GameObject MonsterPrefab { get; }
}```
```public class CombatController : MonoBehaviour
{
[SerializeField] private MonsterSO monster;
private GameObject currentMonster;
private void SpawnMonster()
{
currentMonster = Instantiate(monster.MonsterPrefab, new Vector3(0, 0, 0), Quaternion.identity);
}
Why does it not find monster.MonsterPrefab?
Because it's private
Either make it public, or keep it private (and make it a field since having it as a property is pointless) and make a seperate get-only property to get the field.
is it possible to write an attribute for a field that will make it so that when the field was modified in the editor, it launches a specific method?
I made one before but it's stinky
without the dumb OnValidate
1 sec
stinky? Interesting
Just bad in terms of performance
ObserveChangeAttributePropertyDrawer: https://hatebin.com/jmnwniuyqq
ObserveChangeAttribute: https://hatebin.com/zqfqzmcqbt
Example: https://hatebin.com/tgwekohnac
No doubt there are better ways to do this
is there any reason to make the fields on my Monster SO private?
or can I just make them all public so I can access them?
are these 2 fine to have in Editor folder?
havent really wrote an attribute before
jg curioused
The point is enforcing strictness and readability. If you make everything public then there is no control over what changes the field. You should make everything private or internal until you need to modify it somewhere else.
ObserveChangeAttributePropertyDrawer in the editor folder, ObserveChangeAttribute in the runtime folder
Should have mentioned that. That's why they're split
Because the attribute is something you implement on fields which is runtime related, and the drawer is the thing invoking editor code when it does its behaviour
Just know I made this years ago and I barely worked on that project
So idk how reliable it is
lemi try to add it after my 10 mins debugging sesh
makes it useable for me (goodnews) 
or not 
What's the actual question though?
Hello, what is LayerMask int value for only read object in Layer 0 :Default?
If you find bitwise ops difficult, you can define the layer mask in the inspector.
You can also generate it from the layer names using the GetMask method. Check the API docs:
https://docs.unity3d.com/ScriptReference/LayerMask.html
But to answer you question, it should just be 1, as you need to shift 1 left 0 positions.
I'm trying to add trees to my terrain but the below code doesn't work. It doesn't give any errors but the trees just don't appear. Any ideas?
public static Terrain terrain;
public static GameObject treePrefab;
public static void AddTrees(Terrains terr)
{
terrain = terr.Terrain; // The terrains terrain
treePrefab = Resources.Load<GameObject>("Tree9_2");
TreeInstance treeInstance = new TreeInstance();
treeInstance.position = new Vector3(Random.value, 0, Random.value);
treeInstance.prototypeIndex = 0;
terrain.AddTreeInstance(treeInstance);
terrain.Flush();
}```
how can i compare two vector2's to check if they are similar to a certain decimal point?
floating point precision is around 10^-6
right, at some point you can just do ==
You could also do enumerable.range
thanks
Is there any good lib to extract .zip on IOS? (Async support?) Pls ping
https://forum.unity.com/threads/unizip-free-zipper-unzipper.220589/
Found this one. Maybe it's good, maybe not, you can test it out. Seems like it's simple enough
It seems has problems exactly with IOS 💀
Yeah thats what im using now, but it doesnt have async
That doesn't matter, you can make it async
await Task.Run(() => ZipFile.ExtractToDirectory(...));
Dont like the idea to create a new thread/wrap in task (any pray for task scheduler)
Problem with that, it could be scheduled to main thread, and extract is blocking call
90 MB would take some time to extract 😔
No it's not
Anyway i'll try, ty
What is not?
Unless I'm mistaken, in which case you just need to call the Task Factory instead
This code is not invoked on the main thread since it does not use Unity's synchronization context, as far as I am aware
The thing with your question is that you're looking for a system that will still use this synchronization context when it's asynchronous, so you need to do it manually anyway
Hence why you should make your own Task
If that does not work, you need to go one level lower and instantiate your own thread and run that
Either way the main issue is avoiding the use of that synchronization context and a third party library would not fix that
can getting transform.position and comparing it to other transform.position be noticeably slower than raycast2d? if transform has a lot of parents, getting it's global pos is not that good idea?
you use Vector2.Distance to compare how close two GameObjects are . . .
i need to feed it two global vector2 positions, right?
yes, because their local position is only relative to their parent, unless both GameObjects are under the same parent. also, avoid passing in their transform; only pass in the position . . .
so, 2d devs do that over raycasting? i just wonder if there are some not so obvious downsides
How do I limit a generic to be a primitive type? I.e, T can only be int, long, double...
you can use either, but checking the distance between two GameObjects isn't a heavy task. the best choice is to have one GameObject constantly check its distance two a list of GameObject using both options and check the profiler to determine which is best for your game . . .
a similar approach is unmanaged, c# has no keyword of constraint on primitive type afaik
T : struct ?
i will go with distance check i think, thank you!
constrain to struct, IConvertible . . .
ty
INumber in Unity when
Hey! anyone here using Neovim on Linux? I got the LSP kinda running but it can't find unity libraries (can't find namepsace when using UnityEngine so the code completion/suggestions dont work.
When I pause my game. The default cursor shows and my crosshair disappears. When I resume, the crosshair appears and the default cursor stays there until i click my screen, then disappears. Any help?
So, i have 3 types of entity class, (Entity and 2 derived class: Enemy and Player).
I have an Attack class too, that have 2 child class: EnemyAttack and PlayerAttack.
Enemy have a public Attack list. How can i have a PlayerAttack list and an EnemyAttack list INSTEAD of the Attack one into the derived class?
i can use the virtual and override keys for variable too?
assuming you've pressed the escape key to pause, that releases the cursor from the game view window in the editor meaning you have to actually click back into the game view window in order for it to capture the cursor again. this is expected behavior in the editor
That should stop happening after the game is built I believe
I'll try a build and run
Now you've said that
it makes sense
pressing ESC enables the editor to be in focus so mouse comes into play. fml
it works in build and run
Thank you ❤️
What library do I need for Random.Range?
I have using UnityEngine, but it still won't work
UnityEngine and System both have a Random class. if you have both using directives in your class, you need to specifiy which namespace of Random you're using . . .
Without using, you must provide the full name of the thing you want. So, for example:
UnityEngine.Random.Range(0f, 10f);
using lets you omit that.
hence the error stating there is an ambiguous reference between the two . . .
using UnityEngine;
void Whatever() {
float x = Random.Range(0f, 10f);
}
but, as the error states, both UnityEngine and System define Random
I generally avoid using System; and just write out the full name of anything I need from that namespace
e.g. [System.Serializable]
ah lol thx, yeah I tried adding UnityEgine in front, but it threw another error (I had bad code) 😛 works now ty
If you want both, you can still fix this:
using UnityEngine;
using System;
using Random = UnityEngine.Random;
This will clear up the ambiguity.
Yeah, I was thinking about alternatives to INumber since it is not supported yet
yep, an alias will work just fine . . .
Guess I'm gonna go with IComparable
not even using System, dunno why it's there, removed it
I thought Unity had support for .net 7?
Your IDE may be auto-inserting using directives as you type
No it has been .NET standard 2.1 for a while
You can use newer C# language featurs with some tweak
I'm a little fuzzy on all the different .NET flavors
Unity supports 3 flavours of .Net. .Net Framework 4.7.1 and .Net Standard 2.0 and 2.1
sheesh, when's the 4th?
Tech year 2018
Worse thing is .Net Framework 4.7.1 is still the best as Standard 2.0 and 2.1 still do not implement some features available in Framework
Ah, I see. I got confused then.
too many versions of everything nowadays. i'll just keep learning how to GameObject and MonoBehaviour with unity for a job . . .
To make matters even worse remember that Unity uses the Mono implementation of the .Net libraries not the Microsoft one
they're really behind on everything, huh? sad times . . .
yep a move to .Net 7 is way beyond due and will solve a huge amount of cross-platform problems
this has very little to do with how you implement your game
beyond which APIs you can or cannot access
oh, i know. just saying that i'll mind my business elsewhere and not worry about different standards for certain features since that is all over the place for many assets, etc. . . .
it's interesting to here that there are multiple versions of .Net available, similar to assets, but isn't complete or up-to-date . . .
can you change the type of a navmesh agent in the code?
How do you put an UI element (in my case a slider) in front of a GameObject/Sprite?
ui elements will always display on top of GameObjects (if using screen space ui) . . .
Are the gameobjects children of the canvas?
yes
Welll.... there you go.
Use a sorting layer to put it behind. Or have it not as a child
If I remove the game objects and the slider from the canvas, they disappear
the slider must be part of the canvas . . .
Why remove the slider? And what is the z position of the objects and the camera?
But the slider should be a child of a game object bc it should only be visible when a certain menu is active and this menu is a game object, but it should obviously display in front of the menu
Also, the script which toggels the menu is in the canvas
Then use a sorting layer like I suggested 🤷♂️
Or a worldspace canvas for the slider
But how can I add a sorting layer to a UI element?
UI elements use hierarchy order to sort
you can use two cameras. one for ui using depth only and set that camera for the canvas. make sure the main game camera culling mask does not have the UI layer . . .
I tried to use a 2nd camera now, but I cant get the camera do display everything in the place the main cam displays it
try following this: https://www.reddit.com/r/Unity3D/comments/dtdc5z/unity_tip_if_you_use_screen_space_camera_and_dont/
see if it works . . .
ty
it worked, tysm! Now I just got to get my slider to work, but I hope I'll be able to do that by myself!
Hello everyone !
I have a problem with the scenes in my game.
I have a "MainMenu" scene, and scenes for my game levels.
Starting the game, the main menu behaves normally, lets the player go to the level they selected (which is a new scene). when they get back to the main menu, some things do not work correctly.
I think it's because it's basically returning to the same MainMenu scene it first created, going through its Start function again, even though some things were left over ?
Is there a way to tell Unity to clear totally the scene instead of taking the one it created before ?
One of the things that do not work correctly when going back to the MainMenu, is the functions affected to the PlayerInputs in the Start of the MainMenu.
I tried to use a boolean to only add them to the first call of Start, but even that is not great : it looks like they're reading old values of some booleans, and not doing things correctly.
Do you guys have any advice on ho to handle that ?
using UnityEngine;
public class ZombieBossParticleActivateWhenAnimationPlays : MonoBehaviour
{
// Reference to the Particle Systems on the zombie boss's fists
public ParticleSystem[] fistParticles;
private Animator animator;
private bool particlesActive;
private void Start()
{
// Get the Animator component of the zombie boss
animator = GetComponent<Animator>();
particlesActive = false;
}
private void Update()
{
// Check if the specified animations are playing
bool isPlayingSpecifiedAnimation =
animator.GetCurrentAnimatorStateInfo(0).IsName("Combination boxing zombie quad punch") ||
animator.GetCurrentAnimatorStateInfo(0).IsName("Combination boxing zombie punching bag 2");
// Toggle the Particle Systems based on animation state
if (isPlayingSpecifiedAnimation && !particlesActive)
{
// Start the Particle Systems
foreach (ParticleSystem particleSystem in fistParticles)
{
particleSystem.Play();
}
particlesActive = true;
}
else if (!isPlayingSpecifiedAnimation && particlesActive)
{
// Stop the Particle Systems
foreach (ParticleSystem particleSystem in fistParticles)
{
particleSystem.Stop();
}
particlesActive = false;
}
}
}```
Unless you have anything set in a DontDestroyOnLoad object, when a scene is exited, it's completely obliterated. Every object in it is destroyed and nothing persists. When you load the scene again, it's just like the first time
If that's not what you're getting, then you've got something that's persisting between scenes like a DDOL or some sort of serialized data
I am trying to get my combo boxing zombie boss to make 2 particle systems that make his fists glow when he does a combo punch animation.
Both the particle systems would switch off after he does the punching combo animation.
The particle systems on the zombie boss model, as a child of his fists.
The animation is from mixamo.
I turned the particle systems of when they are a child of the fists, and I adjusted the particles correctly on the fists.
Chat GPT wrote me this script but its not working for the particles systems to switch on when the combi boxing zombie boss does the 2 animations:
Combination boxing zombie quad punch
Combination boxing zombie punching bag 2
Can you help me get it going?
If you want to play particles when an animation starts, and stop them when it ends, this sounds like a textbook use for Animation Events
https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
Why doesnt Unity allow me to create a slider object?
slideFPS.cs(8,12): error CS0246: The type or namespace name 'Slider' could not be found (are you missing a using directive or an assembly reference?)
did you set up your IDE for unity?
Do you have the right using at the top of the script?
Also, your !ide is unconfigured
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
No, see the color of monobehaviour
oh
But definitely configure your ide before anything else
#💻┃code-beginner message
yes I will
ty
Should items be created using scriptable object or oop?
Not mutually exclusive concepts
Does this even makes sense?
Yes, these could be scriptable objects as well as using inheritance
Item could be an SO instead of a Monobehaviour
So when I want to do it this way, when I create a list it will be a type of "Item" and it will store all item types? So will there be one list storing tooli tems, healing items, block items...?
yes
So when I create items they don't show up in inspector. Why is that happening?
Where is that code?
!code
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
In a random start method just for testing
Did you change those to ScriptableObjects?
Do I have to do that?
Well, if you haven't changed anything they're MonoBehaviours
I just updated and configed my VS2022, but now Unity for some reason only opens my files with VS2019
which cannot be created with new
Ok, I see
Gotta change the path in the External Tools menu of Unity
So basically I have to create a SO class which will store all settings and then create new SO item and set it's value to that Item class settings?
ideally you want SO to have immutable data to copy over a plain c# object , store the c# object onto the SO
You could. Or you can instantiate the monobehaviour. Or you could use a Plain Old C Object (don't inherit from anything) and use new on that
I agree with Nav, I don't like to have mutable SOs
https://paste.myst.rs/yex72rod
This was my old item SO. Can I do something like that?:
public class HealingItem : ItemType
a powerful website for storing and sharing text and code snippets. completely free and open source.
Done 🙂
It is VERY helpful haha. Nice work
Ty
also, you can set the slider to only allow whole numbers . . .
anything that inherits ItemType will be an SO still
Is there an efficient way to generate a random number with discontinuities/unity
I've thought of two solutions using a another random number to change the range (1 correspond to x1 to x2 2 to x3 to x4)
Or just using if statements, but is there a less intensive way?
wdym discontinuities
could always store them in arrays and randomize that
you need to randomly choose between an array of ranges, then get the random number from that range . . .
Okay that's what I was gonna do
But just wanted to check if there was a more built in function
int number = Random.value <= 0.5f ? Random.Range(1, 11) : Random.Range(20, 31);
Debug.Log(number);```
xD
Exactly it thanks
I am using a Profile SO to save data between scenes. After typing a name the player presses a button to accept (the bit in the else statement).
public void AcceptProfileName()
{
string lProfileNameString = fInputFieldText.text;
if (DoesProfileExist(lProfileNameString) || lProfileNameString.Length == 1)
{
Debug.Log("You didn't enter a name or that name already exists!");
}
else
{
_playerProfile.CreateNewProfile(lProfileNameString);
//display new profile on screen
_activeProfileManager.SetActiveProfile();
// Load to game selection scene
SceneManager.LoadScene(_GAMESELECTIONSCENE);
}
}
Part of the SO.
public void CreateNewProfile(string aName)
{
_name = aName;
_coins = "0";
_collectionScrollList = new List<string>();
_itemNameList = new List<string>();
_itemPositionList = new List<Vector2>();
SaveSystem.SaveProfile(this);
}```
This works as expected. I can play the game get coins on populate the JSON as expected.
```json
{
"_name": "Profile1",
"_coins": "16",
"_collectionScrollList": [],
"_itemNameList": [],
"_itemPositionList": [],
"name": "Player Profile SO",
"hideFlags": 0
}
The problem comes in when I try to load a selected profile instead of creating a new one. I load the profile, display it on the screen, then immeadiately load into the next scene.
else
{
Debug.Log("Before: " + _playerProfile._name);
_playerProfile = SaveSystem.LoadPlayer(_thisText.text);
Debug.Log("After: " + _playerProfile._name);
//Load Game Selection
SceneManager.LoadScene(_GAMESELECTIONSCENE);
}
The first debug line will return the name of the previous profile that I loaded, the next one will return the one I am currently trying to load. The correct profile will briefly show then the one that I previously load will show.
Once in the next scene the profile I just loaded (shown above) will not be shown nor in the SO. Is there a reason the SO wouldn't hold the data? (Here is my load method)
public static PlayerProfile LoadPlayer(string aProfileName)
{
string lPath = Application.persistentDataPath + ProfilePath(aProfileName);
PlayerProfile lProfile = ScriptableObject.CreateInstance<PlayerProfile>();
if (File.Exists(lPath))
{
string lJson = File.ReadAllText(lPath);
lProfile = JsonConvert.DeserializeObject<PlayerProfile>(lJson);
}
else
{
Debug.Log("File not found! " + lPath);
}
return lProfile;
}
Not entirely sure what your issue is but mutating an SO will have it refer to some other instance rather than the asset SO. It's probably not what you'd want to transfer data between scenes.
I have no problems changing what I use to transfer data between scenes, what would you recommend?
I was using Dontdestroyonload but I had issues when going back to previous scenes and read that you shouldn't use it for things like that. (idk I am still learning)
Either save data to and from disk or DDOL Singleton etc
Saving/ loading to disk between scenes doesn't cause too much overhead? I know my game is small and it won't matter but just thinking of being efficient.
Or a static class that reads data initially from disc etc
Hello, I have this code for simulated suspension. However the wheelObject always moves down by -springLength and if the tank flips then the wheels clip through. I need to somehow get the direction in which they should move on the Y axis
wheelObject.transform.position = Vector3.MoveTowards(wheelObject.transform.position, new Vector3(transform.position.x, transform.position.y - springLength, transform.position.z), 0.3f);
If you're doing it often and not caching data, it would have some cost.
Hmm, ok. I think I will look at droping the SO for a static class to see if that fixes my problem.
Thanks!
I/O operations are probably some of the most slow tasks you can do
Definitely don't want to be doing that like every frame and what not
It shouldn't be done on the main thread in any case
Definitely wouldn't be doing it that often. It is a game of small math problems so it would only be done at the conclusion of each math problem/ scene transition.
Save profiles as jsons then pull them all in profile choose menu discard everything what wasnt chosen and set profile u gonna use in somewhere only one read
Yep, that is exactly what I am doing. I was storing the current profile(the one selected) in a SO for scene transitions but for w.e reason the SO isn't getting updated after a scene transition.
yea weird I was on project like month ago turret defense game turrets are upgradeable and those upgrades persist permanently was stored in SO lots of modifying them but each one had its own asset to edit and didnt use ScriptableObject.CreateInstance whatever that does
didnt have a single issue
It is weird, as soon as I get to a new scene after loading the profile the SO has data for something else. Not what I had in just the previous scene. 😦
A word of warning, scriptable object behave differently in standalone builds. Data you put in them will not be persisted across game restarts
Unlike in the Editor
Hence why it's strongly advised to not change it (mutate it) at runtime
Thanks for that. I wasn't using them for game restart persistance, just for scene persistance.
Ill keep it in mind for the future.
Surprise! Your save system you spent 3 hours making doesn't work in builds
Why don't you make Slider accepts only whole values so you don't need to cast value to int? Documentation
Should the value only be allowed to be whole numbers?
!bug
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
I have it like that already
Dont know why I cast it as well
The slider will still produce floats.
rule of thumb: the type of a member can't change
not unless the object has a <generic type>
List<int> holds int and List<float> holds float
makes sense ig
and float -> int has no implicit conversion
because that almost certainly loses precision
it does have an explicit conversion
which is why you can cast with (int)
kinda not a code question but does anyone know how to fix this
#💻┃unity-talk for question like this - but try restarting your computer
did u try going into task manager maybe u can find it open there lol
done both
Another way you could solve this if you haven’t already is by following the steps: Open the main project folder Enter the folder ‘Temp’ Delete the text document ‘UnityLockfile’ You should be set. It happens alot with me, and this fixs it. When you close unity normally it deletes the file anyway. If it crashes, it may not delete the file. When...
guys, how do I access a child gameobject of an alternate gameobject that I have in the script? (when I say alternate I mean that it is not the one to which the script is applied and you can access it with just gameobject and that's it) I want to access a script of the child object
There's no real difference between the GameObject you're attached to and any other GameObject you have a reference to
GetComponent<Foo>() is the same as writing this.GetComponent<Foo>(), and for components, calling someComponent.GetComponent<Foo>() is the same as doing someComponent.gameObject.GetComponent<Foo>()
so, if you have a field called theObject that stores a GameObject, you can do everything with that object that you can do with the one stored in gameObject.
how could I gobble something really fast to leave like txt file of what happened before the lights go out my game crashes in pc build bruv
Assuming you're unable to determine an appropriate time to log the data due to a crash, you could probably have a finalizer attempt to do stuff before memory is freed with regular c# objects - an extreme case
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/finalizers
Reminder that
Whether or not finalizers are run as part of application termination is specific to each implementation of .NET.
a native crash will not really leave time for anything to happen at all
I want to get started with shaders. I will use them to render some simple shapes for now, like a circle, based on an object. How should I go about it?

i am not clear what "based on an object" would mean
Like a circle would be a struct with center, radius and color.
Hello guyz , i have some problem with my code , i'm sure that this is a stupid error of newbie xD
I want to outline a block when i'm looking at. And turn off the outline when i'm not looking at anymore.
I made a script where the outline work at the first time i'm looking at the object , but dont turn it off when i'm looking somewhere else.
The script is turned off when i launch the game , turn off when i 'm looking object and suppose to turn off when i'm looking somewhere else
Please help me xD
store Outline inside a private var
If you look from one outline-able object to another, you will not turn off the first outline
Two steps: decide if you're no longer looking at the old object, then decide if the new object can be outlined
ahh also why are you using gameObject as the name
thats a big conflict
was clear for me , i 'm a really beginer ahah
gameObject already is the gameobject the script is on
thats because you should almost never use GameObject as type to store
yeah i understand , but how can i do those steps ? with a state var ?
rather store the Component , eg Outline
yes, store the Outline itself
Your logic is currently this:
- If you are looking at an outline-able object, outline it
- Otherwise, if you are not looking at an outline-able object, stop outlining the object you were previously looking at
Instead:
- If you are not looking at an outline-able object, stop outlining the object you were previously looking at
- If you are looking at an outline-able object, and it's not the same as the previous object you were looking at, turn off the outline on the previous object
- If you are looking at an outline-able object, outline it
i guess you could simplify that to
- If the object you're looking at is not the same as the previous object you were looking at, turn off the outline on the previous object
- If you are looking at an outline-able object, outline it
how can i store outline ? i can make a private var get component ?
store it like you store literally anything else
make a variable of the appropriate type and store a value in it
so, declare Outline previousOutline; in the class, then do previousOutline = hit.transform.gameObject.GetComponent<Outline>(); to store something in it
and how would it make work better ?
because its actually doing the same things but juste a var stored no ?
Well, right now, the moment you stop looking at a thing you can no longer change its outline
You have no reference to it once it stops being looked at
So you store the outline you've looked at before and compare it to what you're currently looking at, and if it's a different thing, you use the reference to the old outline to disable it
Just store it in a variable of Outline type instead of a game object
previousOutline is not very useful if you instantly overwrite it
Check if the object you are currently looking at has an Outline
if that's a different outline than previousOutline, turn off the old outline
anyone know how to attach "animator.SetBool("isjumping", false);" to my ground check so it stops the jump animation once i hit the floor instead of looping? (im really new to scripting)
just...call the method?
if your ground check says you're on the ground, then run animator.SetBool("isJumping", false);
If shaders are even the way to go
What kind of approach could I go for having an enemy spaceship always fly towards player in 3D space, but avoiding collisions with planets?
Shaders can certainly be used to draw shapes -- you put it on a quad (a square mesh)
Pathfinding. It needs to trace the path and the navigate it
A* is one such algorithm
that's a good way to do pretty UI elements
i'm sorry , how could i check if the object have an outline ? Ihave to make two var like old var et new var , that in a first way when i'm looking at an object change the bool newvar and when i find another newvar different that the old newvar , put the old newvar to oldvar and turn it off ?
try to get the outline.
if the outline is not null, the object has an outline
or, even better
is there some kind of basic pathfinding I could try to implement instead of trying to make 3 dimensional A*?
if (someObject.TryGetComponent(out Outline outline)) {
// do stuff with the object's outline
}
this creates a new local variable called outline
I would start with something that flies straight at the player
then, I'd raycast forwards and, if a planet is hit, steer away from the planet's center
If the planet density is low, this will work well.
A* is neither 2d, nor 3d.
But yeah, what fen is saying would be simpler for sure
well, it'd be A* with a graph representing 3D space, and creating that graph is non-trivial
even more non-trivial than usual!
you can look at the player, move towards that direction, and use raycast to check for collisions in the direction of movement and find a ray that doesn't intersect to change it's direction . . .
Okay thanks guys
Absolutely
you could also use an overlap query to find all nearby planets
This sounds a lot like "boids" to me.
at least, the first part of boids: separation
Yeah, I saw someone use it in his video. I assume it's due to optimization and GPU-compatibility reasons.
I still don't know where to start, most tutorials are about post processing shaders and stuff like that, which is not very helpful to say the least
anything that's too close to you makes you want to move away
go in the shader graph and try doing some math based on your UV coordinates
Uh well, I don't even know what shader graph is tbh
then start there! unity should have some tutorials for that.
Oh I didn't know there are ui elements like this, this is very helpful
Try attaching various nodes to the output to see what the values look like
I'll give it a look, thanks
i'd start with an unlit shader graph
red is X, green is Y
I struggle with this because I'm partially red-green colorblind 🫠
but anyway -- feel free to ask in #archived-shaders if you have more questions. that's the best spot for this
It's just a Plane (GameObject -> 3D -> Plane)
its UV coordinates range from [0,0] in one corner to [1,1] in the other
this shader just directly outputs the UV coordinate of each pixel as the color of that pixel
So basically, there's a plane, with some material, the material has this shader and the shader is calculating the pixels on what I assume is a texure?
There is no texture involved here.
A texture is an image that you can sample colors from.
This shader does not use one. It just turns the UV coordinates directly into colors.
neither does this one, which is literally always red
So this renders on the plane directly?
Well, it's unlit, so it doesn't care about lighting at all. But I wouldn't say it's any more or less "direct" than any other shader
(also, check the pinned messages in #archived-shaders for shader graph documentation)
Hmm, I suppose a comprehensive introduction to shaders would be most beneficial to me, thank you for your time!
I have a laser wall in my game that rises using a animation, but i also want it to be reversed the next time the animation is enabled, can i change the animation speed during runtime?
without using multiplier
"multiplier"?
Hey
Someone that can help me out could text me on the DM?
I have a lot to send and i need help with my code
Ask your question here.
Ok then
@radiant moon for code use the instructions here
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Sure of course. It shows how to do that in the instructions near the bottom
My code here
oh ok
backticks not apostrophes
CreateObstaclePair(startPositionX, Random.Range(minH, maxH), obstacleGap);
i am creating a flappy bird copy to test things out and the obstacles are not randomizing in position
you'll need to show more code than that
I have a sword as a child of the player. I want the sword to move in relation to the player, but its just going to a specific x and y in the map.
public class SwordController : MonoBehaviour
{
public Transform swordCursor;
public Vector3 defaultPosition;
public Quaternion defaultRotation;
public float rotationSpeed = 5.0f;
void Start()
{
defaultPosition = transform.position;
defaultRotation = transform.rotation;
}
void Update()
{
if (Input.GetMouseButton(0))
{
if (swordCursor != null)
{
//Point towards SwordCursor Object
Quaternion targetRotation = Quaternion.LookRotation(swordCursor.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
}
else
{
// Smoothly move back to default position and rotation
transform.position = Vector3.Lerp(transform.position, defaultPosition, rotationSpeed * Time.deltaTime);
transform.rotation = Quaternion.Slerp(transform.rotation, defaultRotation, rotationSpeed * Time.deltaTime);
}
}
}
the only thing not working is the randomization of the obstacles size
if you look in the inspector for the GameLevel object, what is the value of the minHPossible variable?
hello, i'm topping my question. I can't find any solution to the issue
me too
I NEED HELP
How can I learn more about the unit, I watch the tutorial and I feel like I just memorize the code and do it, and that's really boring man, I want to learn it myself
!learn
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
i have a side scrolling platformer where i want the player to be able to create blocks, would physics.boxcast be a good way to ensure the space is available before creating the block, or is there a better way i could go about doing it?
this is bad
I want to learn camera by myself
OverlapBox actually
A boxcast is like firing a cardboard box out of a cannon and seeing what it hits
Open Unity, learn by yourself. Done.
omg
An overlap box is checking if things exist inside of a cube in world space
good to know, thank you!
I can't do it man, Some things I always need to see a tutorial and the things I can do, and because I memorized some codes
Not sure what else you expected. "I want to learn but not use tutorials" -> "Then figure it out yourself" -> Surprised pikachu face
please help me
You're being silly. If you want to learn, use a tutorial and practice what it shows you. If you don't want any tutorials, then tinker around and figure it out yourself (you likely won't be able to).
Otherwise, read the Unity Docs if you're so inclined.
@unkempt locust i would recommend just following a tutorial of a game genre that interests you, youd be surprised how quickly the training wheels come off and you start doing things on your own without needing to copy the tutorial. i went through one brackeys series (tower defense) and things started to click for me
Lets start with this. What are you EXPECTING? What kind of help can we give you?
aint no way so many ppl got baited on 
||Free 1-on-1 tutoring in a voice call with on-demand DM support||
You severly underestimate the neediness of people that post in this channel
if someone could look into it i'd really apreciate it, i posted the full code further down
here
Log positionX inside of SpawnObstaclePair and see what values you're getting
Investigate if those values are what you expect them to be
You may better remove that sus link from your profile @unkempt locust
Its delivering 100, which is the point of origin where the obstacles spawn
So, it's always 100
how do i make it random
minH and maxH are both 100
Now, try logging those and see what they are, and log the values that make them up
Find out where the math isn't mathing
A value is different than you expected it to be
Ok
https://hatebin.com/zmiteecdas what is this param: actual param thing called I want to turn it off ide prioritizes that over actual variable if name is same between methods but idek what that is what I google for
You mean method parameter? A parameter that you pass in when using a method
does Transform have a sortchild method?
setindex feels weird to be the only option to sort heirarchy via code
no u just set appropriate indexes in a loop and its sortchilds method with extra step 
this what me is doing now 😭
item.transform.SetSiblingIndex(craftableCount);
RecipeHolder elementToMove = RecipeHolders[i];
RecipeHolders.RemoveAt(i);
RecipeHolders.Insert(craftableCount, elementToMove);
looping a duplicate list
AAA so u can pass in variables in any order with this huh cool
hopefully it still help, I only just realized how long ago you asked 😅
yep
looking for advice on how a reccomended way of having a health bar under every mob would be
without having too many canvases etc
Thanks for sharing! I wasn't sure about optional parameters I saw somewhere and now looks clear, thanks! 
public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10)
```Like this one
just use a worldspace canvas
look in your canvas, and change it to world space
also not a code q btw, but pretty sure that's should be enough to send you off
i know but should all the heathbars be in one canvas?
yea just keep using that canvas
If you’ve used raycasts before, you probably also used optional parameters without realizing! Check out the method signature https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
It would be more performant to use canvases for each health bar, or at least more than just one, from what I understand.
See UI optimization tips:
https://unity.com/how-to/unity-ui-optimization-tips
Yeah, I've used raycasts with start, direction and out var for the result, but what I'm not sure is this equal symbol in one of Unity attributes:
[MenuItem(@"CONTEXT/Component/Duplicate", priority = 501)]
```Do you know why it's `priority = 501` not `priority: 501` ?
That’s a c# attribute
It has a couple of different rules. : is used to specify what the attribute is attached to https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/reflection-and-attributes/#attribute-targets
Well, if I look at the documentation you sent earlier it's showing colon symbol but in the script I sent you it's equal symbol
I don’t really see how it’s related to the attribute, but this screenshot shows you how to bypass the optional string parameter
Yes, and colon symbol : is being used. For the script I've sent it's equal symbol =
// original method
ExampleMethod(int required, string optionalstr = "a",
int optionalint = 10)
Different ways to call it:
ExampleMethod(3, "b", 10); // 3 b 10
ExampleMethod(3); // 3 a 10
ExampleMethod(3, optionalInt: 7); // 3 a 7
The screenshot you showed is an attribute, not a method
Attributes use square brackets []
Okay, thanks. So it seems optional parameters for methods use : and optional parameters for attributes use = and that's it? 
is there any difference between string optionalstr = "a" and [Optional] string optionalstr as param actually theres some regarding default value I cant set it to [Optional] case lol
Yeah I understand that but I was asking about the attribute
My understanding is that generally you'd use = when referring to the declaration/definition of something and : when explicitly referring to an argument of some parameter (the second is a newer pattern that helps you explicitly assign values to default parameters in any ordered you'd prefer).
alright, thanks!
hi, im somewhat new to unity, and I noticed that when I use OnTriggerEnter or OnCollisionEnter or any of its variants, it doesnt only checks the collision with the collider attatched to the object holding the script, but also any collider in its children GOs, is that supposed to happen?
if so is there a way for me to specify which collider to check on those methods?
or am I supposed to make multiple scripts and GOs and have each holding their own collider and script and make them exchange info with the main object?
It's called a "compound collider". Any child colliders would belong to a rigidbody up the hierarchy. If you want them to be independent physics objects, add a rigidbody on them or one of the parents(to make a compound collider(.
oh so if none of them have a rigidbody then then the parent wont check the collision of colliders attached to its children is that right?
So, i have a list of Attack, a class that i've created.
Attack need to get access to an entity, another class.
When in my Entity i add the attacks on the list form the inspector, how can i give the reference of this entity to the attacks / how can i let the attacks thake the reference of the Entity where the list is?
That's right. Though, do note that they would not be considered a movable physics object.
You can't(aside from maybe initializing the whole list in OnValidate). But you can pass it during initialization(awake, start). Or when it actually needs it. Why would an attack need a reference to it anyway?
cause must check the buff on the Entity
You don't need an entity reference for that. Especially not as a field in the attack. When do you need to know the buffs?
The attack damage is a property that needs the list of buff every get
Maybe instead of making it a property, calculate it during the attack. The attack would probably be initiated from the entity, so you can pass all the required info there.
so no way to get the Entity from the Attack? WOuld be good to just put in the costructor on the attack, if possible
heh it's a little bit more complicated. I'm going into the property solution for now.
There are ways, as I mentioned in the edited message, it would just sort of lead to a spaghetti code if you ask me.
maybe i can just pass it during the start at the whole list yeah...
Typically, you'd have one way reference hierarchy. Both way reference is not a great practice.
it's a simle solution and should work
If it's not a MonoBehaviour, sure. Otherwise you can't have a constructor.
an example of both way would be transform and gameobject's refs to eachother, ye?
unity devs with the code smell 😠
You can have a property on any class/struct. But you wouldn't be able to reference them in the inspector in the same way.
Anyways, even if it's a MonoBehaviour, you can just create a custom Initialize method to call instead the constructor.
if u post ur exact setup it would be easier to spot what u can do with that list of attacks btw
Yeah. Properties are a c# thing, not unity
Yeah. I don't mean that it's an absolute rule. Besides, unity has to break many rules to make it convenient to the users. Wether that's a good thing or not is debatable.
Forsure Forsure 🤝
i don't like this
@calm coral rude. I wanted to see what happened at 100%
this is what it is, Windows is disappointing 
how would i make it so that if a wall comes in between my character and the camera it becomes slightly transparent
Probably a shader could do it, but you could simply linecast from the camera to the player and change the alpha of any walls it hits
Someone linked a thing from URP that could do it recently, lemme see if I can find it
Oh, it wasn't just urp
#💻┃code-beginner message
I'm trying to destroy an object using Destroy(); but how can I get around this error?
Can't remove RectTransform because Image (Script), Image (Script) depends on it
You can't destroy a Transform anyway
It's not possible to have a GameObject without a Transform
but i want to destroy the gameobject
but im trying to destroy the whole object not the transform
thank you
What did you pass into Destroy?
woops i just noticed i passed in a parents child which is the transform
gyat 50$ ima make one with the line cast method
thanks though
I was dealing with nasty crash in build tried logging everything what comes in from Application.logMessageReceived but nothing, somehow by chance I got editor to crash in same way and editor logs did have my error in there how come? How can I access that deeper level of logging bruh idk what would I do if editor logs wouldnt saved me 3hrs into this
particular error was file lock from what I understand so kinda makes sense if its out of that event territory ig but damn thats a weak ass logging if u ask me
Ah yeah, I didn't actually look at it lol.
There should be some crash logs in the build as well. They might not be as verbose, but there's no way, it just ends without any mention of the crash.@ashen ferry
And a development build should have around the same level of verbosity as the editor I think.
yea so I migjht be retarted
where do u find pc build logs or did u mean my logging should of been close enough to editor logs
every Transform has exactly one GameObject and every GameObject has exactly one Transform. It's very reasonable to have them reference each other like that in that situation.
it was sarcasm bro


I have wave based game and I want to make a timer that displays and continuously updates. How would I do that...I tried OnGUI but it would not update jus remained static
OnGUI only draws to the screen for one frame
so it's very unlikely that it's not changing!
perhaps your timer isn't counting up
can I do anything about this here I tried lambda trick ive found but it still doesnt compile tho can always pepper around #if ig
public void OnGUI()
{
// Increase the time in minute:second format
int mins = Mathf.FloorToInt(elapsedTime / 60);
int secs = Mathf.FloorToInt(elapsedTime % 60);
// Display the time on the bottom right of the screen
string time = string.Format("Time Survived: {0:00}:{1:00}", mins, secs);
GUI.Label(new Rect(Screen.width - 100, Screen.height - 100, 100, 50), time);
}
this is what i currently have
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Well, apparently you can't subscribe to a method that has a conditional attribute 
im giga sleepy but looks like it still leaves in the method just takes care of the calls? But method param uses enum which I cant have in builds either tbh that attribute lowkey useless
#if UNITY_EDITOR
// your code that's supposed to run in edit mode
#endif
```Well, instead of conditional attribute you can wrap it around if statement
yea thats what I do usually but I saw conditional attribute few days ago
tried to flex around it
yea yea sure
The player should emit its own log. Check the pinned messages in the unity talk channel for paths to logs. Or the manual page.
How can I make a script that lerps to a specific index in a horizontal layout group. I want to lerp the layout group object to put a specific child object in view. Im currently just figuring out raw positions. Is there any other ways?
whys it only going up and across
You set the y component of vector3
Your animator uses z component so i think you want to set the z of the movement vector
sorry but im confused
I'm not sure you know what "lerp" means because "lerping to an index" doesn't make any sense. Indices are integers and lerp gets you a discrete value some percentage between two points
Is your issue with movement or animating
movement
Sorry I won’t use lerp in this idea. I just want to move the object with the layout group to the position of a specific index of that layout group if that makes sense
And what is happening that you don't want happening
im going up on the y axis and im ment to be bound to x,z
brb
You could have two objects, one in the layout group that is invisible but the same size as your "real" component, and your real component that is set to always move towards that objects position. You change the index of the fake empty box and the real panel moves to where it is
Do you know what order the three values in a vector3 are?
I'm making a card game and progress is going fine but I'm completely stumped on how I'm supposed to program chain links? Basically chain links are something that goes, turn player activates an effect(chain link 1) then the opponent is given a chance to respon with an effect and if they do that effect is chain link 2 then you are able to respond with a card effect. So after both players say no to further activation, the chain resolves, resolving every effect that was activated in chain.
I've pretty much got my cards moving and summon able and they can attack and use effects but I just didn't implement chain links at all cause as I have figured, they seem hard to do. Any tips? How should I go about doing this?
Do you know what order the alphabet is
yes.
So what comes after X
So if you have a vector where the first thing is set to horizontal, that's x
And if you set the one after X to vertical
Which one did you set to vertical
up
Which is what letter
y
Correct. So, you have a vector where the horizontal axis is x. The vertical axis is y, and 0 is z
So when you move your object by that amount
Which letters are changing
ty i didnt know that vector three had to be in abc order
What's your current implementation of your card game phases? I'd assume you just cram that logic inbetween placing cards down.
Ideally you've a statemachine set up
y and x
Correct. So that would mean the object is moving sideways and up/down
I've created coroutines for that
Coroutines for the animations, but not the actual logic, right?
oh wait, I did some logic such as animation window popping up.
I did realize that you can't do every phase changes so I did change those.
I do not have statemachine
Yeah, it's fine. Something to look into if you go start up another similar project, but polling the state each update is fine. Do change your statements to include 'else if' however so your code can fallthrough without checking each 'if' condition.
forgive me im a slow learner im still a little stuck
You get axis on the same axis
And you should normalize the movement vector (you can use getaxis raw here), since the speed(magnitude) of “diagonal” movement is faster if you press a/d and w/s same time
yea
Anyway, throw me some information on where these chains should be involved. I don't play too many card games but I think I know what you're talking about.
And perhaps some situations that would require to be resolved
When a unit(the creatures or monsters of this game) attacks or moves, they declare attack/movement an after the declaration the turn player is prompted to activate a card if that card is activatable. The other instances are when a player activates their card effect, the opponent can activate their card effect. At the end of each phase should also allow both players to chain a card.
new vec3().normalize (or movement=movement.normalize after you initialize the movement vector)
it should be working tho right
"When a unit(the creatures or monsters of this game) attacks or moves, they declare attack/movement an after the declaration the turn player is prompted to activate a card if that card is activatable. "
This would just be another condition to check and then prompt the user if it's possible. If accepted, then it will have to wait until input for the opposing player to make a move or decline. It would just be in a state of resolving, ping-ponging between player inputs, and until it resolves you just keep going back into this state.
It's a subsection of logic that would probably apply in different phases, so probably some additional methods.
Hi, im working on a ecosystem simulation game. Im wondering which is better for the creatures, using prefabs or using scriptable objects for each species?