#๐ปโcode-beginner
1 messages ยท Page 592 of 1
what do you wanna see?
which components (show inspectors) are on all the objects involved (the player, the ground)
Your movement code
Any code involved in the spawning or the dying
So? I didn't ask when you started, I'm asking you to provide more information so I can help you
I want to see the inspector window for your player object and for the ground
select those objects, take screenshots, and share them here
I would also like to see the code you have on your player for movement
can i show on vc?
You can show it here

jordan what you showed me i dont understand

you just showed me code stuff
ok now.. the player, and the code?
please go check !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
And the code?
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
Can you select your player object in the scene view and show its gizmos?
Probably the CC is just underneath the terrain
Also please don't share code as a video ๐ญ
ok
what
Just select it and show the gizmos
Make sure gizmos are turned on
we want to see the green capsule
To see if it's above or below the terrain
Whyu is there a separate capsule collider
remove that
and show the parent object
we want to see the CharacterController, not this separate capsule
CharacterController should never have extra colliders - that will cause issues
I think just having that second collider can cause your problem in the first place
how do i make it so it wont be seperate
not sure what you mean by that question
make it so what won't be separate
You should remove the Capsule Collider component
ok
Whats code for player?
Whatever you want it to be
you just gotta believe
are you replying to the stuff above or is that a new question lol
I mean the code controlling this thing from above problem
(vencord my beloved)
is your tab key broken
yup 
then use spaces because holy fuck, everything at the same indentation level is near unreadable
(not my code btw, just stole this from the deleted message with vencord)
Not sure but maybe problem is that charactercontroller .isGronded maybe is not true when it "should be"
CharacterController's grounded property returns true only when the previous call to .Move collided with the ground. You need to make sure that you're calling Move exactly one time per frame, and that you always have gravity at lest a little bit even when standing on the ground
Yo stupid question but what does that "?" mean in his code
that's against tos ๐ค
Bro is admitting his crime
damn, im going to discord jail 
I'm pretty sure it just means it could be null
anyway, off-topic
it's like a good safety thing
Type of dude that would say "sigh here officer I stole that candy there, arrest me"
anybody who actually cares is normally a loser dw abt it
Makes sense
null-conditional operator
it is the ternary operator, not the null conditional operator
Okay I just looked it up
oh wait yeah my bad. misread
It's basically a if else cond
I find it funny how I was tweaking at basic scene switching but reverse engineering stuff is like super easy
Locked in fr
float timer += (IsFast ? 10f : 1f) * Time.deltaTime;
is there any benefit though
With?
personally I think a full if statement improves readability
condition ? yes : no
Write this as an if statement
If ur too lazy to type + it's easier to make a game
for clarity
yeah I'd do that with the first part as an if
although still a lot I don't know
I'll try using some when I get back at my pc
been suffering trying .net maui ๐
really I'd rather just have a float rate variable instead of an IsFast bool in the first place
And wherever you would have done IsFast = true; you just do rate = FastRate; instead
then no need for a branch at all
I'll go inline if it's going to be very simple and unlikely to change
Is there a way to edit a color using a color wheel directly in Visual Studio?
no
Not in VS but in the Unity inspector yes.
what about it
I was wondering if that's a feature that VS Code has.
As two of us said above, no.
Right. Originally I asked about VS.
Oh sorry, VSC vs VS
no
VSC doesn't have that
but I'm sure you could write a plugin for it or VS to add it if you really wanted.
In general VSC has the least support for Unity things of all the supported IDEs
Got it.
if you'd have to change a color enough times for it to be useful, then you're better off just making it a variable and doing it in the inspector
I've never used VSC for Unity, only VS, that's why I was asking.
Rider has this thing
When Ive written webgl in vscode, ive used an extension which let you set a vec3 via a colour picker
you know I specifically looked for this and couldn't find it!
It's kinda hidden but under ๐จ icon https://www.jetbrains.com/help/rider/Coding_Assistance__Color_Assistance.html
ah yep there it is
How do u guys deal with layer (names)? 
I want to put some constants somewhere but do u have some other suggestions?
Deal with them in what sense?
I find it rare to need to refer to specific layers in my code.
If you mean for layer masks, they're best configured in the inspector, IMO
how do i fix thisd
As mentioned before can you show the CC gizmo in scene view?
this?
stop what you're doing and go check !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
It's quit4e clear from your earlier screenshot that the capsule object is offset by 10 units in the air
So your actual CC is definitely below the terrain
Fix the offset of the child object and move your object above the terrain
Recording program that has "record started" toast is so bad
this is the child object
i will try lower
show the parent object
And look at the damn inspector
your child is offset by 10 units on the y axis
Aight.
Basically you have this problem
so if its exactly on the y axis it will work?
Use your eyes
position the CharacterController above the world
and position the visual capsule (child) such that it lines up on the parent
Which should be 0
This is not magic, you can reason about this yourself
Also making sure this is set to Pivot will help you (in top left of the scene view)
alright bro
bro what is the parent
OHHHHH
bro player is already at 0
Have you looked at it yet and checked where the gizmo is yet?
the green outline of the CharacterController
Like in my screenshot
so the parent needs to be below the child
oh ok
I'm literally jsut asking you to look at the green outline and make sure it's above the terrain
and you should have the child line up with it as well
TBH there isn't a good reason for you to have a MeshRenderer on the child object either if it's a first person game but that's a separate issue.
ok
i will make the green outline on the top
its always on the bottom but i will try
What do you mean by top and bottom
before you change anything can you just show a screenshot of the character with the gizmo visible?
Do you understand what was wrong now?
yes
the parent wasnt on top of the platform which made me fall down
sorry for making you go through the trouble
i am gonna work on my survival game now
thanks again
can someone tell me why this doent make the player rotate with the camera? my guy still goes forward, left, right, backward, indepentant of where the player is looking
i do, i have vs code and all the extensions n junk
i can clearly see it isn't fully configured in the screenshot you posted
how so?
you don't have syntax highlighting for unity types
that is not the only step and is covered by the link that was already provided to them
if they have actually gone through all of the steps in that link then they need to go through the troubleshooting steps here: https://unity.huh.how/ide-configuration/visual-studio-code#if-you-are-experiencing-issues
Share your entire script
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
is vs code configured yet
https://hastebin.skyra.pw/obamezuriz.pgsql
this is the mouse look around
i went throught the vs code turtorial its all there
did you go through this #๐ปโcode-beginner message
because:
#854851968446365696
I belive ive gone through this before, its all configured right acording to the vs code tutorial, and all the trouble shooting in this link does nothing
then show that vs code is configured. if you truly did follow all of the steps then it will be properly configured
okay now show vs code to show that it is actually configured
and fun fact: if nothing has changed then it is not configured still and you didn't bother following all of the troubleshooting steps
yeah, so i swaped the orientation from the movement script from the player to the camera in the player. and now instead of not rotating with the camera, the camera ignores all mouse input and the moment you move your mouse you levatite into the sky while spinning right
I added a set gravity to true or whatever in private void start(), and that seems to fix it, even the wweird camera stuff
How do I fix this? I'm trying to unlock the player's cursor while they hold tab, I dont know what's wrong with this code snippet. there's no compiler errors but it just doesnt do anything
private void Cursorunlock()
{
//Crouching
if (Input.GetKeyDown(KeyCode.Tab))
Cursor.lockState = CursorLockMode.Confined;
if (Input.GetKeyUp(KeyCode.Tab))
Cursor.lockState = CursorLockMode.Locked;
}
show the cursorlockmode code
oh i thought i included it, my bad.
private void Cursorunlock()
{
//Crouching
if (Input.GetKeyDown(KeyCode.Tab))
Cursor.lockState = CursorLockMode.Confined;
if (Input.GetKeyUp(KeyCode.Tab))
Cursor.lockState = CursorLockMode.Locked;
}
I'm not the best with C#
void Unlockies()
{
playerScale = transform.localScale;
Cursor.lockState = CursorLockMode.Confined;
Cursor.visible = true;
}
I swear to god if i send the wrong code again
!code
and where are you calling these methods
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
what do you mean?
in a playermovement script, if that answers it.
i mean if the method is not being called then obviously the code inside it will not execute
hold on one sec
i see now
so you're asking when cs Cursorunlock() is used in the .cs file?
yes, that is how you call the method and i am asking where it is being called
great question
i think unless if youre checking if its locked or unlocked everytime its not gonna do anything
you could call a method in there and pass in locked or unlocked
A tool for sharing your source code with the world!
yeah i found that out
also make sure you copied the code correctly because there is at least one compile error in here. however that may have just been due to copying it incorrectly
I accidentally deleted something imma fix that
A tool for sharing your source code with the world!
I thought it wasnt being used anymore
im confused on how this works Cursor.lockState = CursorLockMode.Confined;
what is confusing about it
I'm also using unity 6
What does the docs say?
what
confined means it's stuck inside the window
is it a built in unity function thing
I believe so
Did you check the Unity docs to see what it means and what it does?
im talking more about c#
CursorLockMode is an enum, Confined is one of the members of that enum. Cursor.lockState is a property of the static Cursor class and that property is of type CursorLockMode
ohh ok
You asked about Cursor.lockState; that is from Unity. You can google it to get information about it . . .
I asked because I thought you looked it up and were confused about its meaning, so I wanted to get/see which part of it confused you . . .
oh im more confused about like whats going on like id get if you were setting that to like true or an int or string or something like that
but its an enum which im still a little confused on how that works
enums are basically just named ints
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum
My code works now! thanks!
an enum is basically a named integer. I would search: "enum C#," to get information about it if you're confused. That's usually my first go-to . . .
yeah ive learned about them im trying to see if i understand how its used in this case
it's just that; a named integer
the name helps keep it in sync when devving, being an integer means it's lightweight and has limited values
ok i dont get why you use it and add the locked or confined like do you check if its CursorLockMode.Confined why wouldnt you set it to like locked or like 1 2 3 for each state
Similar to how usually you can use 1 and 0 in place of true and false
oh but not in c#
lmao
giving it a name makes it much easier to read
you basically are using 1 2 or 3, it's just that those values happen to have nametags so the intent of the int is clearer
ok are the .locked and confined defined in the code or like is it a unity functioni
yes, those are members of the enum
oh i didnt even know you could have enums in enums
huh?
You should look at a tutorial about enums first . . .
that's not what he's saying lol
You are confused about how they're created and used . . .
no i get it i had a wrong conception
this is the definition of the CursorLockMode enum: https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Input/Cursor.bindings.cs#L20C1-L30C6
i thought you would have an enum like
enum
state
locked
confined
but you name the enum
yes, CursorLockMode is the name of the enum
wouldnt it be like enum state
locked confined
None, Locked, and Confined are the memebers of the enum
i literally linked the actual definition of the CursorLockMode enum if you want to look at how it is defined in the code
no clue what you mean here tbh
oh so like you could do cursorlockmode = 2 and it would equal confined?
like you name the enum and have the members in it
if you cast the integer 2 to CursorLockMode then it would be equivalent to CursorLockMode.Confined, yes. but you don't just do CursorLockMode = 2 because that makes no sense
you could think of the enum as something like this```cs
public static class CursorLockMode
{
// Normal
public static int None = 0;
// Locked to the center of the game window
public static int Locked = 1;
// Confined to the game window
public static int Confined = 2;
}
more like public const int since they are constant
the enum members are based on integer values, but they aren't equal to the integer values
you just define the ints so it will work right?
(that wouldn't need static, right? im not familiar with const, and i forgot about that aspect lol ๐ )
you can still change None here
you dont store any data in enums ?
not really, no
An enum is just a number wearing a nametag, and when you compile the game, the nametag gets lit on fire so you are left with the number.
some do, like java (though i don't know of any others) and others like c# would need a separate mapping for that
yeah i really didnt get the point before because i thought you did
They're just identifiers, much like the naming of your class
imagine making a class and have no name to it, how do you identify it as is?
(That's default behaviour in godot)
you can also do that in c# and java, can't you (just not in unity)
Seems like a terrible idea, cause then you're using directory pathing as the identifier lol
you can only do it for the entry point, so literally yes lol
anonymous main class, something like that
I'm creating procedural terrain from a plane and for some reason when increasing the number of subdivisions of the plane from 7>8, I get a weird bug
8 subdivisions:
on the right of the mesh there's a weird stretched triangles that doesn't appear on any subdivisons <8
Here's the code:
https://paste.mod.gg/wwxmkkumuzcg/0
A tool for sharing your source code with the world!
it also causes a weird lighting error but nevermind that for now
Hey everyone, can anyone help me with properties (get and set) in Unity C#? I already know how to use them, but I'm wondering if they're really necessary. What are the use cases for properties in C# for Unity? Isn't it easier to just use a public variable instead of properties?
Using a public field gives everyone access (no ownership) to outside scripts to not only retrieve (get) the value, but also change (set) it. A property handles encapsulation by controlling access to the value and can be used to check or implement events for that property . . .
thanks for the answers. But I'm still wondering why its really necessary when i can use simple vaiable declaration. sorry if im asking some dumb qn.
is it something to do with optimization?
i'd recommend reading through all of the responses on that stack overflow post i linked
How would I implement Random.Range to randomly select an index of an array but make it so the chance of selecting the same index twice in a row is lower than selecting a different index. I've looked up that you can put the results into a list and do a check each time to see if that number is already in the list but that is if you never want to do the same index twice whereas I simply want the chance to be very low.
just the previous index?
yes
it's kinda arbitrary so you'd have to do this with logic instead of any elegant structure or math
just keep the most recent selection in an int variable, if it chooses that reroll once, then if it chooses that same index again you don't reroll because now it has chosen it with a much lower chance
or look into implementing a weighted random selection. that will be more complicated and will take more work but it will give more flexibility to the system
Does no one know?
i would've thought it had something with the sheer number of vertices/triangles being created but idk for sure
that seemed to do the trick thanks!
I have a question about the DrawQuads example on the docs
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/GL.QUADS.html
How is mat passed into the draw call here?
Also is GL.Vertex 3 a world space co-ordinate or screen space co-ordinate?
Ooh
So this is part of the matrix stack?
Right now I need to draw a bunch of lines(with thickness and materials) so I wanted to use unity GL for this
I dont want to manage a pool of LineRenderers
I just started unity today and am doing the 'roll a ball' tutorial I've gotten to this bit where the ball is meant to move when I click my arrow keys but it literally just doesn't work. I don't know what went wrong because I followed everything. Here's my C# script if there's any errors in that
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public float speed = 10.0f;
private Rigidbody rb;
private float movementX;
private float movementY;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void onMove(InputValue movementValue)
{
Vector2 movementVector = movementValue.Get<Vector2>();
movementX = movementVector.x;
movementY = movementVector.y;
}
void FixedUpdate()
{
Vector3 movement = new Vector3(movementX, 0.0f, movementY);
rb.AddForce(movement * speed);
}
}
I don't see anything wrong with the code so far, are there any errors that appear in the console?
You may need to check on how you set up the Input Action.
also !code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
And what is calling onMove
Im trying to procedurally generate a top down 2d dungeon, planning to hand design a few and spawn them in randomly
My approach is 1 tilemap as prefab for each room so 20 room is 20 tilemap
Want to know if there better solution ?
if you're using the inputsystem for messages, it should be OnMove, not onMove
I do not know
I'll try that in a couple of minutes
oh my god you fixed it, thank you so much. I had no idea it was so specific.
casing matters in code
OnMove would be a separate method from onMove, and the inputsystem/unity are specifically looking from OnMove
Thanks dude i'll make sure to remember this
hey, my camera wont rotate for some reason
like player camera, it was working fine a day ago
Depends on the matrix you push to GL
Did you end up drawing thick lines as quads?
You can set line width? For me the base line size is enough for now
I used GL.Lines
Afaik GL.Lines only supports 1 pixel line width
I just asked because you mentioned thick lines
Just saw this
What's your camera rotation code?
Any errors?
give me a sec opening unity
Nope, none at all.
// Update is called once per frame
void Update()
{
//gets mouse axis
float mouseX = Input.GetAxis("Mouse X") * mouseSens * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSens * Time.deltaTime;
//Y axis rotation
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90, 80);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
//X axis rotation
playerBody.Rotate(Vector3.up * mouseX);
}
the camera wont rotate, the playerBody will
Which part of this code controls the camera?
Also !code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
public class MouseLook : MonoBehaviour
{
public Transform playerBody;
public float mouseSens = 100f;
float xRotation = 0f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
//Locks mouse cursor
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
//gets mouse axis
float mouseX = Input.GetAxis("Mouse X") * mouseSens * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSens * Time.deltaTime;
//Y axis rotation
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90, 80);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
//X axis rotation
playerBody.Rotate(Vector3.up * mouseX);
}
}
the update method controls the camera
actually the entire thing is for the camera but "playerBody.Rotate(Vector3.up * mouseX);" and "transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);" control camera movement specifically.
Update isn't controlling the camera
Its for mouse movement
Did you parent camera to playerbody at some point?
its always been parented
Hello new to unity here, why the -xRotation, is it inverted?
camera is a child of player
what?
xRotation -= mouseY
Is playerBody the same as/the child of player? I'm not sure what your project looks like, make sure camera really is a child of playerBody
Here's the hierarchy @eager spindle
Which one is playerBody?
Player has the script and Player_V is the visual
Also where's the camera?
Player
ViewCamera
Do you have multiple cameras in the scene?
thats xRotation = xRotation - mouseY, just syntax
nope
Could you take a video of this?
Oh okay you're only dealing with mouseY here
alright
@eager spindle it looks fine, but feels very floaty and unresponsive
don't multiply your mouse input by Time.deltaTime, mouse input is already frame rate independent
i already tried removing it. Doesnt affect a thing
I mean at the very least, your rotations should have felt sped up
and would have had to lower sensitivity
Is this just an inconsistent frame timing problem? Can you record with the stats window open?
ah wait
the original problem just happened
i cant move my camera at all
its due to an animation
without the animation it works fine
v without the aniamtion ^ with the animation
@dusty geode
Is your animation modifying the player rotation or the camera rotation? If so you need to remove those properties from the animation
yea its modifying camera rotation but i dont see why thats a problem
Its a problem because your script and the animation are modifying it so they are fighting
can you suggest a possible fix?
remove the camera rotation from the animation
ok but can i still acheive camera rotation
yes your script should be in full control of the camera rotation
thats not my question
What is your question?
currently, when the gun is shot, it triggers an animation
you say its because it rotates the cmaera
so how can i still acheive the same effect without compensating camera rotation?
You need to control the "recoil" through script or have another parent object inbetween the player and the camera which you animate instead
a simple playerCam.Roatate(); then?
playerCam.transform.Rotate(new Vector3(-60f, 0f, 0f));
does this work instead?
That's going to be instant, you probably want it over time.
yea
I would try an intermediate object between the camera and the player and apply recoil animation to that either through animation or script. I have never implemented something like this myself, so that's about the extent I can answer
I think a lot of games do this, they essentially have a root camera object which animators can mess with without affecting the scripting of the camera look rotation
that would be a lot of work considering i have a few animations
actually
you mean like an empty game object?
Yes so,
Player
CameraRoot
Camera
If I remember correctly, this GDC covers it briefly.
In this 2015 GDC session, Bungie's David Helsby shows how Bungie creates high quality first-person animation that supports Destiny's cutting edge gameplay.
Update: Due to a technical error, the last portion of this talk is not currently available on YouTube or the GDC Vault. We do apologize for the inconvenience.
GDC talks cover a range of d...
i cant parent Camera to CameraRoot for some reason
ok nvm i did it
thanks, it works now
Yo is there a yt channel or a website from where i can learn c# for unity
Do you know any c# in general? If not then don't limit yourself to only unity specifics
https://www.youtube.com/watch?v=jGD0vn-QIkg
Brackeys got some videos for general c# that he's done on the side of general Unity videos and I think they're worth a watch.
Let's write our first code in C#!
Jason no longer offers the course mentioned in the video.
โ Watch the Getting Started Video: https://youtu.be/N775KsWQVkw
โ My Solution to the Challenge: https://forum.brackeys.com/discussion/746/brackeys-solution-to-c-tutorial-01-challenge
https://forum.brackeys.com/discussion/746/brackeys-answer-to-c-tutori...
I just know python
I'll give it a shot ๐
I scoured the videos and they are simple enough for an introduction
His videos are fine for introductions, besides a few bad apples
I honestly would recommend this, it probably covers more and is straightforward
https://youtube.com/playlist?list=PL4LFuHwItvKbneXxSutjeyz6i1w32K6di&si=pwSN2M8noAuTzAx2
Followed by this
https://youtube.com/playlist?list=PL4LFuHwItvKaOi-bN1E2WUVyZbuRhVokL&si=hbFH6T9qDQOETEtg
stupid question, I have the player instantiate some prefabs on the screen. I have an undo button which is supposed to destroy the last spawned object.
I added a stack and I'm popping it when undo is clicked, but I don't need a stack at all, right? Every time a new object is created, the variable is changed, so I can just simply destroy the object, right?
My stack appears to be useless.
I asked here cuz there were a lot of tutorials on yt n i didn't know which one to follow just to come here n each one of u recommend their own preferences ๐
well if you want to be able to undo many times in a row its useful right?
I'm grateful but confusion still exists
Oh, you're right, I do need it then. But does that work? Like, when I destroy the game object variable, can I pop the previous one from the stack and destroy it?
What are you confused about?
hi im new to unity, im trying to make a rhythm game but i could seem to make a note spawn. what do i do?
Which course to follow to learn c#
fix it so that it spawns?
in other words, how do I reference the object from the stack, rather than my game object variable?
You would try pop, if you get a value you destroy the game object.
When you spawn a new one, push it onto the stack.
I mean ultimately it's up to you, but the videos I linked are solid, I've watched them in the past
more views does not mean better
Tru
yes yes, but how do I actually reference the popped object, rather than the game object variable created irrespective of the stack?
what? you pop and it returns the reference and you use this to destroy...
if(stack.TryPop(out GameObject ob))
{
Destroy(ob);
}
that works but the example above prevents a failed pop in a slightly more efficient way
No but I can't reference it unless I add the out etc part, yea?
also
I'm doing if (BlockStack.Count > 0), so no need for trypop I guess
well you do GameObject popped = stack.Pop() otherwise
trypop is essentially doing that behind the scene
yeah I figured
its like dictionary.TryGetValue()
This worked, than you very much!
now I just gotta give the player back the money for the object ๐
You are familiar with the concept of methods returning values right?
You can also google a function and check the docs for how it works https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1.pop?view=net-9.0#system-collections-generic-stack-1-pop
then the best thing is to check the docs and then you would see that you Pop() to remove AND get the top value
c# docs are great so go read it when you need to
I honestly didn't even think of that, I added Pop() and forgot that it doesn't actually delete the game object in the scene, just from the stack lol
slow witted, what can you do
I am working on a unity project with a github repo set up, I just opened my game and it is not showing up, like its gone, I dont know what happened and I have a competion for it tommorow, can someone please help me
you probably jsut need to open your scene
hard to say what you mean by "it's not showing up"
Either the assets are there in the project folder or they aren't.
That...
Its just gone, I dont know how else to describe it
yeah you don't have your scene open
Actually you have no assets either
there is nothing in the assets folder
to back up Prae's point
Well you didn't push them up
there's nothing to freak out about but - wherever you originally made the project you need to push the assets from there
you need to commit them and push them to githuub
Okay, how can I do that?
I have everything pushed to github
Either you didn'tm or you didn't pull it down
idk it's git basics
Show a screenshot of your github repo assets folder
you makle a commit, and you push it
Yep did that
go look at your repo and see if they're there on github
Show us on github
Where is that at?
if they're there then there's nothing to worry about, you need to actually just pull them down
@grand snow so should I make a stack for money taken away at each spawn as well for multiple undos? Don't see a simpler way.
I think I just stashed 4 changes that I didnt want to save
you did something werid with the stash or something
Okay, how can I make it not messed up?
look at the histroy
either just delete and reclone the whole thing, or look at the history and see what you did
You probably want a new class or struct to hold both things (game object, money and other things)
Then you can undo everything a lot easier.
I reverted "level 3" as thats when things broke
if you look in windows explorer are your project files there?
In the future, when you commit, don't push it until you check out the local changes work
Okay, that makes sense
You sure you're opening the right scene?
The asset folder in the screenshot looks totally empty
up here
Yeah, thats what I dont get
Other thing to double check is make sure you have the correct project folder open?
I cant open any scene
How?
look in unity hub
at the path of the project
and make sure it's the right one
or do "show in explorer" on the assets folder in the project window
and make sure there's stuff in it
and it's the correct place
Yeah all that looks good
ok yeah something got corrupted
I would try reverting to the previous (working) commit
Okay, How can I do that
from your Git gui
whatever that app was you were using for git
probably right click on one of the commits in the history
and see the options
Just using git-desktop
yeah i only know how to do it in the command line
you could potentially also download specific branch and start from there
it would be like:
git checkout HEAD~1``` for example to check it out
This is when I right click
you can do checkout commit
to move your head to that for a moment to test it
okay, I checked out the commit and nothing in the editor changed
do actual scene assets exist inside Unity, though?
you can search the project window for t:scene
The paths shouldn't have changed, but...
Guys is it possible to lock my mouse cursor in the bounds of an object?
Like for instance i have a square i dont want the mouse to go out of it?
not with the hardware mouse
if you have a virtual/software mouse cursor, sure.
i can make a custom mouse in unity?
you can make an object that pretends to be a mouse
okok i got it thank you
i would like to ask for help, is this the right chat?
so i want to make a dash in my game, but for some reason when i calculate the directional vector based on cusor location, it pushes the played a little bit below of where my cusor is
the green line is the directional vector
any idea who would that be?
mousePos.z = cam.nearCLipPlane doesn't feel quite right
you probably want mousePos.z = transform.position.z;
or dir.z = 0; after the dir calculation line
Also how are you drawing the green line?
(not sure where the mouse is in the screenshot)
Debug.DrawRay(transform.position, normalizedDir, Color.red, 5f);
Isn't it green?
Debug.DrawLine(transform.position, mousePos, Color.green, 5f) ;
This doesn't seem like the right line
wrong line
That seems ok assuming you fix the mousePos.z thing
still does it
Is the line drawn incorrectly, or something else?
Also - is your camera set to Orthographic, or Perspective?
nope, its visible with the eye that the player isnt going in the right direction
Otho
So the line is drawn correctly?
yes
Then it's your player code that is wrong
In a 2d game - anyone know how would I shift my character so that it flips along a different point? In this image my character is flipping across the red line and I want it to be the green line.
use an extra empty gameobject and flip that instead..
that way u can align ur player within that gameobject where u want the pivot
i think you have a pivot on your sprites moved
ye.. its a sprite.. u should be able to modify the pivot in the sprite editor
the little blue ring is the pivot.
im just a dumbass, the dashForce was Vec2 and i set y force lower than x force
but thanks
using an extra gameobject would be like this..
you'd be flipping Visual and the Sprite is adjusted as a child as needed
I think you are right they are all off in the sprite editor.
well its just centered per sprite i think
yep, move the blue ring to the middle of the character
since its offset u may need to do some adjustments
or crop the sprites empty space in an editor so its fixed resolution and you will have prefect middle
yup.. many many possibilities
so I got to do that on all frames of that image sheet? I see
yup
thats y i made the 2nd suggestion of an empty wrapper gameobject
I was kinda thinking it was that issue, but I didnt want to go through all that trouble to fix it
but its up to you.. and how it ends up working out ๐
trim em a bit more cause that'll display a larger transparent quad (which isn't a biiiig deal in 2D but if you wanted like 3D particles it matters)
awesome, thanks guys
find a good value and Copy-Paste..
save urself some time..
that is if they're all pretty uniform
eh, looks like the running animation is a little hard to line up
gotta move the pivot for each of those frames
๐ถ Rough!
Can I just trim each one and let the center be it or I would have to adjust it manually still?
Hey guys, quick question regarding Unity:
I want to add a GameObject to the scene using code. For example spawning enemies. However I cannot access the Unity project.
Should I create a prefab in Unity and then just add the Scripts to the GameObject or should I build the object in code from the ground (e.g. by creating the entire object hierarchy)?
(Note: I am not a beginner at coding in general, since it's my job and I got over 12 years of experience. However I am not well educated about the Unity API so I am asking this in the beginner channel)
question if i want to start out to make a game on unity what version of editor i should use?
why would you not use the most recent one
i use the recent one but idk if it was the stable one cuz idk how unity work so i prefer to ask
im using the 6 version? which is the recent
yes 6 is latest LTS
well not always stable but at least it gets patched
@rich adder you got any ideas
yeah its polished with some minor bugs
#๐โcode-of-conduct specifically says no modding talk @radiant sage
@slate helm just release ur game and say there were some bugs you didnt know about 
oh mb
fixed tho
I mean its not a modding question
im a beginner so i watn to start out but was unsure
i usually would not use unity but i wanted to give it a try
When you are a beginner you should not be scared about versions
I dont think the Unity devs release garbage
yes because the whole "cannot access the unity project" part
the also why i didnt watn to use unity is cuz the recent thing they added but i heard they removed it so that why
I mean I just want to add a GameObject using Scripts
Well, can I create a prefab and load it as an asset using code?
I mean not really since I cannot access the dll libraries
thats what instantiate does
(except in my project that is not a unity project)
again we cannot help with modding questions soo
Let me rephrase it: Is it a good approach to create a prefab of an object without any scripts and add the scripts to the hierarchy later? Or is there a preferable approach?
This question seems very generalized to me and is outside of any modding context
since im starting out is there a tutorial for me to learn unity?
the whole point of the prefab is to already the contain the wanted components so you minimize what you have to manually add through code
https://learn.unity.com/pathways
Start here from top to Bottom
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
thx
Docs are great. I recommend you to also look on YT videos. Those often contain good practices
YT is 98% crap practices in unity context
So creating an prefab in Unity that contains AnimationController, Rigidbodies etc and then at runtime adding Scripts to the object is good practice?
I mean as a beginner that seems like a good start. as soon as he gets experience he can make up his own mind 
thats like the opposite of what i implied
other way around, as beginner you cannot recognize bad code/ patterns
you first learn the beginning with good structured courses by unity then when you have enough experience you can watch YTs to extract the info minus the bad practices
I agree with you. But again as you get experience over time you will learn how to write good code
I fully agree with that one
You gain shit experience if you're start with shit tutorials. And just like AI beginners can't distinguish shit code and pickup bad practices early
I am still unsure of what to do now :/
I mean true
I guess Udemy courses are a great start then
ehh whatever waste your money on shit courses if you want. Ill stick to the Unity official resources
Nothing beats a documentation. But it took me a few years to properly understand docs (I never actually tried to learn them tho)
not even a documentation thing.. unity has thousands of videos in-house material
oh right I forgot
@slate helm forget what I said. Check the Unity videos, they are a really good resource
they also been bumping their Youtube again with the newest unity 6 components
gotcha
i want to make like a rpg or a turn based rpg game
i do have a model but i need to rig it
mixamo does a great job of automatic rigging
If you dont want to do it
its going to be at least a year or two before you can make something this complex
well my model is not humanoid enough there no arm
I disagree, if he uses a cube without a 3d object that involves animation controlling he can do it in a few days
an rpg in a few days
I'd love to see it
i made this but the rigging is hard
I recommend you to turn down your expectations and start with something more simple
well im talking about a main fight loop only
maybe not a few years depend also of the speed that you work on
not a fully fletched game
exemple i can do modeling like fast i was able to make 3 weapon in the span of 45 min
I agree that a fully fletched RPG as a solo dev takes a few years
mate if you never coded you wont be able to make any RPG any time soon
your expectations might be too high
but since i never touched coding like in C# idk how ti work
I have to agree on that one
then you should start on something way more simple
and my ADD and ADHD dont really help with the focus and attnetion span so i need to also work on that
start with simpler projects first, build up your knowledge
what simple for beginner?
2d platformer maybe
flappy bird n such
with very simple graphics
gotcha
you have to learn basics like game loops and thinking in logic component, using variables etc
rpg setting has 100 times the things to know
i saw there was a editor tutorial in editor thingy in the website for when you in unity but how do i activate it?
you can just visit the unity website and check the docs
they have tutorials for a variety of game types
ye but i mean
did you start with the essentials?
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
exactly mate
if only there were a convenient link to the instructions for that, but we'll never know if that's the case because you cropped it out
after you finish the 1 step (installing unity ) it gives you the assets
the pathway overview dont tell me
sorry...
you have to keep pressing completed.
thats why its a structured course
you have to do the tasks, if you did already mark them completed and move on next
if I want a simple button that is clicked to set bool true and clicked again to set false what would my configuration be through unitys input system.
put the bool toggle in performed?
public bool MyBool;
private void Awake(){
inputs = new();
}
private void OnEnable(){
inputs.Enable();
inputs.Player.MyAction.performed += OnMyAction;
}
private void OnMyAction(InputAction.CallbackContext context){
MyBool = !MyBool;
}```
Thank you, just confused with the new(er) input system. I ended up doing
{
if (value.isPressed)
{
OpenInventory = !OpenInventory;
}
}```
and this for my inventory
void Update()
{
if (starterAssetsInputs.OpenInventory)
{
OpenInventory = true;
} else
{
OpenInventory = false;
}
InventoryCanvas.gameObject.SetActive(OpenInventory);
}
yeah that works too if you use the PlayerInput components
Yea, I am working off starter assets input.
btw you should mind as well take an Event approach instead of polling in update OpenInventory
yes you are right, what is the reason for that exactly? performance?
how can i "set" how interface "get" gets its value
public event Action<bool> OnInventoryToggled;
public void OnOpenInventory(InputValue value)
{
if (value.isPressed)
{
OpenInventory = !OpenInventory;
OnInventoryToggled?.Invoke(OpenInventory);
}
}```
you mean how to implement an interface or are you talking about a property defined in an interface?
how to setup interface at runtime
skips having to poll yes performance is one of them its also cleaner most of the time without a two way connection
okay thank you
can you try being specific for once
yea more info plz
i have class with specific key fields, i want each have custom logic of getting the value defined on its creation
so setting interface logic before its defined
something like setting unityaction and running it later
are you sure you mean interface?
since properties containing validation code require a backing field, this functionality must be defined in the classes that implement the interface. so just implement the interface and use a full property with an explicit backing field
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties#properties-with-backing-fields
yeah property too many names there
Why?
oh so there is alternative of unityaction that can have return value
mh
like Func?
How do I fix it?
If you just have a delegate you can have it return a value. If you use event then the last subscriber value is returned to the event caller.
anyone know how to make a gun fire
raycast
i was about to say american school kids for sure knows but raycast may be better response
Break down what "gun firing" means and do each piece individually
ok
i will watch tutorial
i highly reccomend you go check !learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
hey can someone help me
!ask ๐
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
unity wont let me use visual studio
it says i have to re install visual studio bu i already tried that
where do you see it telling you to reinstall it
it appears a error message every time i try to open a script
show it
and have you tried launching the visual studio installer to resolve whatever configuration problem there is?
yeah , i will try again another time just to be sure
you should try opening the visual studio installer program now to see what it actually wants you to do. the error message isn't saying you need to reinstall, it is saying that the configuration for the install is not complete
Stupid question, how can i initialise a dictionary of monobehaviour objects?
private Dictionary<string, ObjectPool> _pools;
this function is trying to access it
public bool TryFindPool(string name, out ObjectPool pool) => _pools.TryGetValue(name, out pool);
However cant due to: NullReferenceException: Object reference not set to an instance of an object
When i try and do the usual = new(), it complains at me because you're not allowed to do that with monobehaviours apparently, so im not really sure what im supposed to do
Here's my whole script for context:
public class ObjectPoolManager : Singleton<ObjectPoolManager>
{
private Dictionary<string, ObjectPool> _pools;
public ObjectPool CreatePool(string name, GameObject prefab, uint initSize)
{
if(_pools.ContainsKey(name)) throw new ArgumentException($"Object pool with identifier {name} already exists");
ObjectPool pool = new(prefab, initSize, transform);
_pools.Add(name, pool);
return pool;
}
public bool DestroyPool(string name)
{
if(!_pools.ContainsKey(name)) return false;
_pools[name].Dispose();
_pools.Remove(name);
return true;
}
public ObjectPool FindPool(string name) => _pools.GetValueOrDefault(name, null);
public bool TryFindPool(string name, out ObjectPool pool) => _pools.TryGetValue(name, out pool);
}```
you need to instantiate the dictionary with new
the Dictionary is not a MonoBehaviour so that would not cause any issues. if you are seeing anything about newing a MB then you're doing something else
I agree with Box. You need to initialize your Dictionary _pools. You don't do that anywhere . . .
Oh right, that's what i was doing initially but got an error, i'll change it back and let you know the error
Oh it turns out it was due to the fact that i also had a list on my ObjectPool that i missed changing to new() as well and thought the error was coming from the same place, nevermind. Thanks!
hey guys, newb here
I'm using Unity6 and using the new input system, and trying to create a 2D platform game. Very simple one, using a movement script also very basic.
Thing is, in previous versions, I used translate to move the player and addforce to jump, and now I'm using position and can't find my way to script Jump this way.
like this:
any tips?
I wrote in update something like jump = JumpAction.ReadValue<Vector2>();
...but find myself lost here ๐
why did you use MovePosition ?
better use translate?
no use the rigidbody velocity
to make a jump with this You'd have to calculate gravity on your own then apply opposite force up, plus you have to make your own collision detection
in previous versions of unity i used this:
private void FixedUpdate()
{
transform.Translate(Vector2.right * Time.deltaTime * speed * horizontalInput);
}
//jump is on floor
private void OnCollisionEnter2D(Collision2D collision)
{
isOnFloor = true;
animator.SetBool("jumpbool", false);
this is still wrong
you never want to use Translate with rigidbodies, you mind as well teleport its the same thing
yep, know that
This is not the correct way to move a rigidbody object . . .
just change it to do
Vector2 vel = new (xInput * speed, rigidbody2d.velocity);
rigidbody2d.velocity = vel
Especially, placing it in FixedUpdate . . .
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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 you mean xInput, should i use MoveAction or JumpAction?
How can I change the sprite of a game object with a script.
var xInput = MoveAction.ReadValue<Vector2>().x
actuallyi in unity6 you can even use xInput directly without creating new v2
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody2D-linearVelocityX.html
access the spriteRenderer 's sprite property
make a field in the inspector if you want to assign a specific sprite
okay.
*linearVelocity
yeah unity 6+ and above
but for jumping you don't use addforce?
yeah use addforce for jump
I do not understand this error. Could someone help me please?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class redGreenScript : MonoBehaviour
{
public gameLogic logic;
public SpriteRenderer spriteRenderer;
public Sprite[] sprites;
// Start is called before the first frame update
void Start()
{
logic = GameObject.FindGameObjectWithTag("Logic").GetComponent<gameLogic>();
}
// Update is called once per frame
void Update()
{
if (logic.isRed == true)
{
spriteRenderer.sprite = sprites[1];
Debug.Log("Red");
}
else
{
spriteRenderer.sprite = sprites[0];
Debug.Log("Red");
}
}
}
get used to debugging a null reference exception
whatever is on line 21 is null
you cannot access something that is null because computer has no idea what to access
most likely gameLogic was not found on gameobject with tag Logic
also no need to use tags if you're looking for a script
Is it fine to use Math.Infinity on Raycast or it's gonna like... try to check for a lot of points and get messy?
wdym a lot of points?
it only goes as far until it hits something
Like checking the whole line towards infinity
Think of a raycast like a fancy laser pointer
nah it checks hit at the "tip" when something hits, it stops
And you can control how long the beam is
My tag is correctly set up on the Game Object so I don't understand why that would be the problem.
But it doesn't find anything is just gonna keep checking up to infinte or what?
then its a reading problem, see how it says LAYER and not Tag?
It is the only way I have learnt. Is there a faster way?
Doesn't that take like actally forever?
Sorry ๐คฆโโ๏ธ
Screenshot the red green script in the inspector
As in the one that's on a game objects
The Tag literally says Untagged and the Layer says Logic . . .
using strings is messy anyway. forget tags
@rich adder it'll make sense
easier to just do
logic = FindFirstObjectByType<gameLogic>(FindObjectsInactive.Include)
is this object on a prefab?
no
drag the game logic gameobject into the field in the red green script
okay
This is gonna return true if it does find the component, right?
you dont need the generic parameters as it's implied in the out
You don't need == true either
it returns false if the component is not found
I thought it returned null
and out would become null, so you can actually check either
it returns bool and assigns the out parameter . . .
You either use the generic parameter or explicitly put the type . . .
TryGetComponent<DraggeablePlayer>(out draggeablePlayer)
TryGetComponent(out DraggeablePlayer draggeablePlayer)
is the draggeableplayer a type like how an int or a string is
yes, every class, interface, enum, etc that you define in your code is a type
Yes, because you have to put a type in the generic field . . .
So this makes sense?
Basically, everything is a type . . .
yes, however you don't need to access the gameObject property on the collider to call TryGetComponent since it is also defined on Component
You could also chain with &&
also, just FYI but you do still have to specify a type for the variable if you are creating a local variable in place. however specifying the generic type parameter on the method call allows you to use var in place of the actual type for the out parameter
Ok.... so if I want to now move the object along, I cannot use Input.mousePosition raw right? I would need to use a raycast again right?
And tell it to move within the plane of the fist hit?
That's up to game logic
I mean like this
The mouse position uses a totally different metric from the world transform isn't it?
Mouse position is screen space and you can convert it to world space with ScreenPointToRay or ScreenToWorldPoint etc
You are not forced to use raycast
Hey guys just wanted to ask if i have a bool variable and want to reference it in another script is all i have to do is make it public and use it from another script or are there more steps
you need to get a reference to the component that the bool is on, but as long as you do that and the bool is public you can access it
https://unity.huh.how/references
So in this case the ScreenToWolrdPoint would be the one I am looking for?
Again that's up to game design. I don't know what you are making
there are a few other different methods of doing it too (like singletons for example), although yeah that's how you'd normally do it
Are you okay with a fixed distance from the camera to your world point? If so, you can use ScreenToWorldPoint. Do you want the location of the mouse in world space to be accurate to the depth of the objects in world space? If so, you can use ScreenPointToRay
It's 2D, so the Z axis is always 0
then screen to world point would be what you're looking for
im trying to get a score system running and its not working
Ya, I think this should work?
the gameobject that PPtext is on doesnt contain the component Text.
You probably added a TextMeshProUGUI to it instead.
But now I need a collider to detect the hit. I am now wondering... are the players meant to be colliders and the things the can collide with triggercolliders?
Cause I kinda forgot
Oh what should I change text to then?
They might want to use physics for stuff like pushing them around and all that kind of stuff, so not sure
Can I apply physic force to non-rigidbodies?
no, you'd use translation
I want to do stuff like... push them in or away, check if they were pushed into a wall and stuff like that
Not sure if translation is gonna work well for that
That is not.... detecting a hit somehow???
How are you debugging it? (I.e. what's the updated code?)
With a drawLine? Like how else? I don't understand the question
This is checking for ANY non-trigger collider on the Default layer right?
I swapped the buttomdown for a just button to see it clearer
I was more concerned about the print statement than the line
This drawline is incorrect
The second print is just not showing, si it's not detecting anything
DrawLine expects two position vectors
You should use DrawRay instead if you're passing a position and a direction
What's the difference?
If I tell you to move to north that's not a thing
Because north is a direction relative to a position, not a position itself
What did you change and how
I just changed the DrawLine to DrawRay
So nothing should change actually
But I have no idea how that is not returning a hit
Layer is Default, has a collider and a rigidbody too
It's not the default?
But I don't want to create a LayerMask, I want to use just any and all, like the default layer
Doesn't Raycast use that if u don't use the overload for layers?
You're passing a layer into a parameter that expects a LayerMask
doesn't drawRay just draw a line? i dont think it does the collision stuff too
never used it myself. im just assuming it works the same as the gizmos draw ray
I am drawing a line to see where the RayCast is going
Or at least that's the idea
Not sure if that is actually the case seeing the results
oh kk, just realised i've missed a lot in chat. gimme a bit to catch up
Ok, so no fucking idea, so I am gonna close it and go to sleep and with some luck it will be just unity doing weird stuff and will work tomorrow without touching anything
Cause I think it totally should
I'm working on a VR Game, and I cant seem to get the net to interact with physics
Basketball Net colliding with ball, im not sure what the code to get it doing like that is, but i need help
probably a #๐ฅฝโvirtual-reality or #โ๏ธโphysics question
ty fot letting me know
I recently started learning Unity and i am getting this error. Can someone explain to me what does it mean by "cannot be the same as their enclosing type"?
your "enclosing type" is the class
its got the same name as the method
thats a no-no
Yeah, that's a typo. My fault for trying to remember and write the syntax in Discord. I mainly use the generic version like the GetComponent counterpart . . .
eh? what am i doing wrong
What does the error message say? that would help . . .
and it's post to post your !code for us to see. a small snippet doesn't help that much . . .
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
Thanks. Did you check the method from the Unity docs?
Static member 'Foo' cannot be accessed with an instance reference; qualify it with a type name instead
It's a difference between using an instance vs accessing the type . . .
Oh, cool. You have this one as well. About everything is covered on here now. That's awesome!
Yes, but one is red and the other is green . . .
C# is case sensitive
Take a closer look . . .
i have been staring at this for 20 minutes
It's like using a kid to do an adult's job . . .
i will go INSANE from this data persistence project submission they did not teach this well enough
idk what the fuck i'm writing lol
might just give up and copy the code but if i do that i dont learn anything
i also havent really gotten back to coding 'normal game' stuff for the past 5 days i might start forgetting things so i really gotta start on my own personal game lol
Hey all, is there any way i can still use Instantiate in this script without requiring it to be a monobehaviour?
public class ObjectPool : MonoBehaviour
{
private Queue<GameObject> _pool = new();
private GameObject _prefab;
private Transform _parent;
public ObjectPool(GameObject prefab, uint initSize, Transform parent)
{
_prefab = prefab;
_parent = parent;
for (int i = 0; i < initSize; i++)
{
GameObject instantiatedObj = Instantiate(prefab, Vector3.zero, Quaternion.identity, parent);
instantiatedObj.SetActive(false);
_pool.Enqueue(instantiatedObj);
}
}
public void Dispose()
{
foreach(GameObject obj in _pool)
{
Destroy(obj);
}
_pool.Clear();
}
public GameObject DePool(Transform newTransform)
{
if (!_pool.TryDequeue(out GameObject obj)) obj = Instantiate(_prefab, Vector3.zero, Quaternion.identity, _parent);
obj.transform.SetPositionAndRotation(newTransform.position, newTransform.rotation);
obj.SetActive(true);
return obj;
}
public void RePool(GameObject obj)
{
_pool.Enqueue(obj);
obj.SetActive(false);
}
}```
I'm trying to create an object pooling manager, and im creating a dictionary of these objects here:
```cs
private Dictionary<string, ObjectPool> _pools = new();
But unity doesn't like the fact that im using new() on monobehaviours. I know i could add it as a component to the manager, but that feels like a janky solution
So do i need to define the logic to instantiate an object within my manager rather than my individual ObjectPool then?