#๐Ÿ’ปโ”ƒcode-beginner

1 messages ยท Page 592 of 1

solemn grotto
#

here

wintry quarry
#

not a super helpful video

#

you'll have to show how everything is set up

solemn grotto
#

what do you wanna see?

wintry quarry
#

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

solemn grotto
#

i am so confused

#

i started today

wintry quarry
#

So? I didn't ask when you started, I'm asking you to provide more information so I can help you

solemn grotto
#

no i am saying

#

idk what that means

wintry quarry
#

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

solemn grotto
#

can i show on vc?

wintry quarry
#

You can show it here

solemn grotto
#

ok

rich ice
solemn grotto
rich ice
solemn grotto
#

you just showed me code stuff

wintry quarry
solemn grotto
rich ice
#

please go check !learn

eternal falconBOT
#

:teacher: Unity Learn โ†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

wintry quarry
rich ice
#

!screenshots

eternal falconBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

wintry quarry
#

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 ๐Ÿ˜ญ

solemn grotto
#

ok

wintry quarry
#

Make sure gizmos are turned on

#

we want to see the green capsule

#

To see if it's above or below the terrain

solemn grotto
wintry quarry
#

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

solemn grotto
#

how do i make it so it wont be seperate

wintry quarry
#

not sure what you mean by that question

#

make it so what won't be separate

#

You should remove the Capsule Collider component

solemn grotto
#

ok

wintry quarry
solemn grotto
#

that didnt do it

#

i removed it

#

it still does the same thing

vital tartan
#

Whats code for player?

polar acorn
#

Whatever you want it to be

rich ice
#

you just gotta believe

rich ice
vital tartan
#

I mean the code controlling this thing from above problem

rich ice
#

(vencord my beloved)

slender nymph
#

is your tab key broken

rich ice
#

yup pensive

slender nymph
#

then use spaces because holy fuck, everything at the same indentation level is near unreadable

rich ice
#

(not my code btw, just stole this from the deleted message with vencord)

vital tartan
#

Not sure but maybe problem is that charactercontroller .isGronded maybe is not true when it "should be"

polar acorn
buoyant shoal
#

Yo stupid question but what does that "?" mean in his code

lethal meadow
buoyant shoal
rich ice
#

damn, im going to discord jail pensive

lethal meadow
rich ice
#

anyway, off-topic

lethal meadow
#

it's like a good safety thing

buoyant shoal
#

Type of dude that would say "sigh here officer I stole that candy there, arrest me"

lethal meadow
buoyant shoal
rich ice
west radish
buoyant shoal
#

Okay I just looked it up

rich ice
#

oh wait yeah my bad. misread

buoyant shoal
#

It's basically a if else cond

west radish
#

yeah

#

It's very useful

buoyant shoal
#

I find it funny how I was tweaking at basic scene switching but reverse engineering stuff is like super easy

#

Locked in fr

west radish
#

float timer += (IsFast ? 10f : 1f) * Time.deltaTime;

lethal meadow
#

is there any benefit though

buoyant shoal
lethal meadow
#

personally I think a full if statement improves readability

lethal meadow
west radish
wintry quarry
#
float rate = IsFast ? 10 : 1;
timer += rate * Time.deltaTime;```
#

I would do this

buoyant shoal
wintry quarry
#

for clarity

lethal meadow
#

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 ๐Ÿ’”

wintry quarry
#

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

west radish
#

I'll go inline if it's going to be very simple and unlikely to change

fading dune
#

Is there a way to edit a color using a color wheel directly in Visual Studio?

rich ice
#

no

wintry quarry
fading dune
#

Oh, I see.

#

What about VS Code though?

wintry quarry
#

what about it

fading dune
#

I was wondering if that's a feature that VS Code has.

wintry quarry
#

As two of us said above, no.

fading dune
#

Right. Originally I asked about VS.

wintry quarry
#

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

fading dune
#

Got it.

rich ice
#

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

fading dune
#

I've never used VSC for Unity, only VS, that's why I was asking.

west radish
#

When Ive written webgl in vscode, ive used an extension which let you set a vec3 via a colour picker

wintry quarry
wintry quarry
#

ah yep there it is

static cedar
#

How do u guys deal with layer (names)? UnityChanThink
I want to put some constants somewhere but do u have some other suggestions?

wintry quarry
#

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

solemn grotto
wintry quarry
solemn grotto
rich ice
eternal falconBOT
#

:teacher: Unity Learn โ†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

wintry quarry
# solemn grotto

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

void thicket
#

Recording program that has "record started" toast is so bad

wintry quarry
solemn grotto
#

i will try lower

wintry quarry
#

show the parent object

#

And look at the damn inspector

#

your child is offset by 10 units on the y axis

wintry quarry
solemn grotto
wintry quarry
#

Fix it by fixing the offset of the child object

#

to 0

solemn grotto
#

ok

#

all 0 right?

#

on the position

wintry quarry
#

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)

solemn grotto
#

alright bro

wintry quarry
#

Player is the parent
Capsule is the child

solemn grotto
#

OHHHHH

solemn grotto
wintry quarry
#

the green outline of the CharacterController

wintry quarry
solemn grotto
#

so the parent needs to be below the child

wintry quarry
#

no?

#

The character controller green outline needs to be above the terrain

solemn grotto
#

oh ok

wintry quarry
#

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.

solemn grotto
#

ok

#

i will make the green outline on the top

#

its always on the bottom but i will try

wintry quarry
#

before you change anything can you just show a screenshot of the character with the gizmo visible?

solemn grotto
#

it worked

#

i am on the platform now

#

thank you so much

wintry quarry
#

Do you understand what was wrong now?

solemn grotto
#

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

kindred pawn
#

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

slender nymph
#

you need to get !vscode configured

#

!vscode

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

kindred pawn
#

i do, i have vs code and all the extensions n junk

slender nymph
#

i can clearly see it isn't fully configured in the screenshot you posted

kindred pawn
#

how so?

slender nymph
#

you don't have syntax highlighting for unity types

dusty geode
#

Check your preferences -> external tools

#

Set the ide to vs code there

slender nymph
#

that is not the only step and is covered by the link that was already provided to them

eternal falconBOT
kindred pawn
#

thats the movement

slender nymph
#

is vs code configured yet

kindred pawn
kindred pawn
slender nymph
kindred pawn
slender nymph
#

then show that vs code is configured. if you truly did follow all of the steps then it will be properly configured

kindred pawn
slender nymph
#

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

kindred pawn
kindred pawn
#

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

runic belfry
#

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;
}
drifting cosmos
runic belfry
# drifting cosmos 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

slender nymph
#

!code
and where are you calling these methods

eternal falconBOT
runic belfry
#

in a playermovement script, if that answers it.

slender nymph
runic belfry
#

hold on one sec

#

i see now

#

so you're asking when cs Cursorunlock() is used in the .cs file?

slender nymph
#

yes, that is how you call the method and i am asking where it is being called

runic belfry
#

great question

drifting cosmos
runic belfry
#

should I send the script?

#

yeah

drifting cosmos
#

you could call a method in there and pass in locked or unlocked

runic belfry
slender nymph
#

you're not calling it anywhere.

runic belfry
#

yeah i found that out

slender nymph
#

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

runic belfry
#

I accidentally deleted something imma fix that

#

I thought it wasnt being used anymore

drifting cosmos
#

im confused on how this works Cursor.lockState = CursorLockMode.Confined;

slender nymph
#

what is confusing about it

drifting cosmos
#

im new btw

#

but the confined

runic belfry
#

I'm also using unity 6

drifting cosmos
runic belfry
drifting cosmos
runic belfry
cosmic dagger
drifting cosmos
slender nymph
cosmic dagger
#

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 . . .

drifting cosmos
#

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

slender nymph
runic belfry
#

My code works now! thanks!

cosmic dagger
drifting cosmos
naive pawn
#

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

drifting cosmos
#

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

timber tide
#

Similar to how usually you can use 1 and 0 in place of true and false

#

oh but not in c#

#

lmao

naive pawn
slender nymph
drifting cosmos
#

ok are the .locked and confined defined in the code or like is it a unity functioni

slender nymph
#

yes, those are members of the enum

drifting cosmos
#

oh i didnt even know you could have enums in enums

slender nymph
#

huh?

drifting cosmos
#

wait

#

i think im thinking wrong

cosmic dagger
naive pawn
cosmic dagger
#

You are confused about how they're created and used . . .

drifting cosmos
#

no i get it i had a wrong conception

slender nymph
drifting cosmos
#

i thought you would have an enum like
enum
state
locked
confined

#

but you name the enum

naive pawn
#

you do

#

you name both the enum and its members

slender nymph
drifting cosmos
#

wouldnt it be like enum state
locked confined

slender nymph
#

None, Locked, and Confined are the memebers of the enum

slender nymph
naive pawn
drifting cosmos
drifting cosmos
slender nymph
naive pawn
#

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;
}

slender nymph
#

more like public const int since they are constant

naive pawn
#

the enum members are based on integer values, but they aren't equal to the integer values

drifting cosmos
naive pawn
timber tide
#

you can still change None here

drifting cosmos
#

you dont store any data in enums ?

naive pawn
#

not really, no

zenith cypress
#

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.

naive pawn
#

some do, like java (though i don't know of any others) and others like c# would need a separate mapping for that

drifting cosmos
#

yeah i really didnt get the point before because i thought you did

timber tide
#

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)

naive pawn
#

you can also do that in c# and java, can't you (just not in unity)

timber tide
#

Seems like a terrible idea, cause then you're using directory pathing as the identifier lol

naive pawn
#

you can only do it for the entry point, so literally yes lol

#

anonymous main class, something like that

neat bay
#

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

#

it also causes a weird lighting error but nevermind that for now

mental hamlet
#

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?

cosmic dagger
mental hamlet
#

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?

slender nymph
#

i'd recommend reading through all of the responses on that stack overflow post i linked

last owl
#

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.

naive pawn
#

just the previous index?

last owl
#

yes

naive pawn
#

it's kinda arbitrary so you'd have to do this with logic instead of any elegant structure or math

slender nymph
#

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

neat bay
#

i would've thought it had something with the sheer number of vertices/triangles being created but idk for sure

last owl
eager spindle
#

How is mat passed into the draw call here?

#

Also is GL.Vertex 3 a world space co-ordinate or screen space co-ordinate?

eager spindle
#

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

rare iris
#

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);
}

}

eager spindle
#

also !code

eternal falconBOT
rugged beacon
#

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 ?

naive pawn
rare iris
rare iris
rare iris
naive pawn
#

OnMove would be a separate method from onMove, and the inputsystem/unity are specifically looking from OnMove

rare iris
burnt stirrup
#

hey, my camera wont rotate for some reason

#

like player camera, it was working fine a day ago

verbal dome
eager spindle
#

I used gl setortho

#

Managed to figure it out in the end

verbal dome
eager spindle
#

You can set line width? For me the base line size is enough for now

#

I used GL.Lines

verbal dome
#

Afaik GL.Lines only supports 1 pixel line width

#

I just asked because you mentioned thick lines

eager spindle
#

What's your camera rotation code?

#

Any errors?

burnt stirrup
burnt stirrup
burnt stirrup
# eager spindle What's your camera rotation code?

// 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

eager spindle
#

Also !code

eternal falconBOT
burnt stirrup
#
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.

eager spindle
#

Update isn't controlling the camera

burnt stirrup
eager spindle
#

Did you parent camera to playerbody at some point?

burnt stirrup
calm flame
burnt stirrup
calm flame
eager spindle
burnt stirrup
#

Here's the hierarchy @eager spindle

eager spindle
#

Which one is playerBody?

burnt stirrup
#

Player has the script and Player_V is the visual

eager spindle
#

Also where's the camera?

burnt stirrup
burnt stirrup
eager spindle
#

Do you have multiple cameras in the scene?

burnt stirrup
burnt stirrup
eager spindle
#

Could you take a video of this?

calm flame
burnt stirrup
dusty geode
burnt stirrup
dusty geode
#

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?

burnt stirrup
#

ah wait

#

the original problem just happened

#

i cant move my camera at all

#

its due to an animation

#

@dusty geode

dusty geode
#

Is your animation modifying the player rotation or the camera rotation? If so you need to remove those properties from the animation

burnt stirrup
dusty geode
#

Its a problem because your script and the animation are modifying it so they are fighting

burnt stirrup
#

can you suggest a possible fix?

dusty geode
#

remove the camera rotation from the animation

burnt stirrup
dusty geode
#

yes your script should be in full control of the camera rotation

burnt stirrup
dusty geode
#

What is your question?

burnt stirrup
#

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?

dusty geode
#

You need to control the "recoil" through script or have another parent object inbetween the player and the camera which you animate instead

burnt stirrup
#
playerCam.transform.Rotate(new Vector3(-60f, 0f, 0f));
#

does this work instead?

dusty geode
#

That's going to be instant, you probably want it over time.

burnt stirrup
#

yea

dusty geode
#

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

burnt stirrup
#

actually

#

you mean like an empty game object?

dusty geode
#

Yes so,

Player
  CameraRoot
    Camera
#

If I remember correctly, this GDC covers it briefly.

https://www.youtube.com/watch?v=CXFLu8cityA

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...

โ–ถ Play video
burnt stirrup
#

ok nvm i did it

#

thanks, it works now

lofty jacinth
#

Yo is there a yt channel or a website from where i can learn c# for unity

timber tide
#

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...

โ–ถ Play video
lofty jacinth
timber tide
#

I scoured the videos and they are simple enough for an introduction

#

His videos are fine for introductions, besides a few bad apples

dusty geode
chrome apex
#

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.

lofty jacinth
#

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 ๐Ÿ˜‘

grand snow
lofty jacinth
chrome apex
dusty geode
pine shell
#

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?

lofty jacinth
chrome apex
#

in other words, how do I reference the object from the stack, rather than my game object variable?

grand snow
dusty geode
#

more views does not mean better

lofty jacinth
chrome apex
grand snow
#

what? you pop and it returns the reference and you use this to destroy...

#
if(stack.TryPop(out GameObject ob))
{
    Destroy(ob);
}
chrome apex
#

aha

#

I was just using MyStack.Pop();

grand snow
#

that works but the example above prevents a failed pop in a slightly more efficient way

chrome apex
#

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

grand snow
#

well you do GameObject popped = stack.Pop() otherwise

dusty geode
chrome apex
grand snow
#

its like dictionary.TryGetValue()

chrome apex
#

now I just gotta give the player back the money for the object ๐Ÿ˜„

grand snow
chrome apex
#

yes I am

#

but I never used a stack before

#

was a bit confused

grand snow
#

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

chrome apex
#

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

radiant glen
#

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

wintry quarry
#

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.

radiant glen
#

That...

#

Its just gone, I dont know how else to describe it

wintry quarry
#

Actually you have no assets either

dusty geode
#

there is nothing in the assets folder

hexed terrace
wintry quarry
#

Yeah you either didn't actually upload them

#

or you didn't pull them down

radiant glen
#

Yeah I know! But I dont know why!!!

#

I am sorry I am totally feaking out

wintry quarry
#

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

radiant glen
#

I have everything pushed to github

wintry quarry
#

idk it's git basics

dusty geode
#

Show a screenshot of your github repo assets folder

wintry quarry
#

you makle a commit, and you push it

radiant glen
wintry quarry
#

go look at your repo and see if they're there on github

wintry quarry
radiant glen
wintry quarry
#

if they're there then there's nothing to worry about, you need to actually just pull them down

chrome apex
#

@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.

wintry quarry
radiant glen
wintry quarry
#

looks like maybe you stashed everything?

radiant glen
wintry quarry
#

your local is just messed up

radiant glen
wintry quarry
#

you did something werid with the stash or something

radiant glen
#

Okay, how can I make it not messed up?

wintry quarry
wintry quarry
radiant glen
grand snow
radiant glen
#

I reverted "level 3" as thats when things broke

wintry quarry
# radiant glen

if you look in windows explorer are your project files there?

timber tide
#

In the future, when you commit, don't push it until you check out the local changes work

wintry quarry
#

restart unity

radiant glen
timber tide
#

You sure you're opening the right scene?

wintry quarry
#

The asset folder in the screenshot looks totally empty

wintry quarry
radiant glen
wintry quarry
#

Other thing to double check is make sure you have the correct project folder open?

radiant glen
wintry quarry
#

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

radiant glen
#

Yeah, it looks like it is

#

When I try to open a scene this happens by the way

radiant glen
wintry quarry
#

I would try reverting to the previous (working) commit

radiant glen
wintry quarry
#

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

radiant glen
#

Just using git-desktop

wintry quarry
#

yeah i only know how to do it in the command line

radiant glen
rich adder
#

you could potentially also download specific branch and start from there

wintry quarry
#

it would be like:

git checkout HEAD~1``` for example to check it out
radiant glen
#

This is when I right click

wintry quarry
#

to move your head to that for a moment to test it

radiant glen
#

okay, I checked out the commit and nothing in the editor changed

radiant glen
swift crag
#

you can search the project window for t:scene

#

The paths shouldn't have changed, but...

errant pilot
#

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?

wintry quarry
#

if you have a virtual/software mouse cursor, sure.

errant pilot
wintry quarry
#

you can make an object that pretends to be a mouse

errant pilot
#

okok i got it thank you

bold falcon
#

i would like to ask for help, is this the right chat?

rough lynx
#

Depends what're you asking for help with?

#

If it's coding then yeah

bold falcon
#

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?

wintry quarry
# bold falcon

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)

bold falcon
#

Debug.DrawRay(transform.position, normalizedDir, Color.red, 5f);

bold falcon
#

Debug.DrawLine(transform.position, mousePos, Color.green, 5f) ;

wintry quarry
#

This doesn't seem like the right line

bold falcon
#

wrong line

wintry quarry
#

That seems ok assuming you fix the mousePos.z thing

bold falcon
#

still does it

wintry quarry
#

Is the line drawn incorrectly, or something else?

#

Also - is your camera set to Orthographic, or Perspective?

bold falcon
#

nope, its visible with the eye that the player isnt going in the right direction

#

Otho

wintry quarry
#

So the line is drawn correctly?

bold falcon
wintry quarry
#

Then it's your player code that is wrong

vapid locust
#

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.

rocky canyon
#

that way u can align ur player within that gameobject where u want the pivot

bold falcon
#

i think you have a pivot on your sprites moved

rocky canyon
#

ye.. its a sprite.. u should be able to modify the pivot in the sprite editor

bold falcon
#

but thanks

rocky canyon
# rocky canyon

using an extra gameobject would be like this..
you'd be flipping Visual and the Sprite is adjusted as a child as needed

vapid locust
rocky canyon
bold falcon
#

yep, move the blue ring to the middle of the character

rocky canyon
#

since its offset u may need to do some adjustments

bold falcon
#

or crop the sprites empty space in an editor so its fixed resolution and you will have prefect middle

rocky canyon
#

yup.. many many possibilities

vapid locust
#

so I got to do that on all frames of that image sheet? I see

bold falcon
#

yup

rocky canyon
#

thats y i made the 2nd suggestion of an empty wrapper gameobject

vapid locust
#

I was kinda thinking it was that issue, but I didnt want to go through all that trouble to fix it

rocky canyon
#

but its up to you.. and how it ends up working out ๐Ÿ‘

timber tide
#

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)

vapid locust
#

awesome, thanks guys

rocky canyon
#

find a good value and Copy-Paste..

#

save urself some time..

#

that is if they're all pretty uniform

timber tide
#

eh, looks like the running animation is a little hard to line up

#

gotta move the pivot for each of those frames

rocky canyon
#

๐Ÿถ Rough!

vapid locust
#

Can I just trim each one and let the center be it or I would have to adjust it manually still?

radiant sage
#

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)

slate helm
#

question if i want to start out to make a game on unity what version of editor i should use?

radiant sage
slate helm
#

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

rich adder
radiant sage
#

LTS means Long Term Support

#

So it should be stable

rich adder
#

well not always stable but at least it gets patched

radiant sage
#

should be stable

#

or will be

rich adder
#

yeah its polished with some minor bugs

radiant sage
#

@slate helm just release ur game and say there were some bugs you didnt know about Shrug

radiant sage
#

fixed tho

#

I mean its not a modding question

slate helm
#

i usually would not use unity but i wanted to give it a try

radiant sage
#

I dont think the Unity devs release garbage

rich adder
slate helm
#

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

radiant sage
#

I mean I just want to add a GameObject using Scripts

rich adder
#

You can by using Instantiate

#

or the Editor class equivalent

radiant sage
#

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

rich adder
#

thats what instantiate does

radiant sage
#

(except in my project that is not a unity project)

rich adder
#

again we cannot help with modding questions soo

radiant sage
#

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

slate helm
#

since im starting out is there a tutorial for me to learn unity?

rich adder
#

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

rich adder
slate helm
#

thx

radiant sage
rich adder
#

YT is 98% crap practices in unity context

radiant sage
radiant sage
rich adder
#

thats like the opposite of what i implied

rich adder
#

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

radiant sage
rich adder
radiant sage
radiant sage
#

I guess Udemy courses are a great start then

rich adder
#

ehh whatever waste your money on shit courses if you want. Ill stick to the Unity official resources

radiant sage
#

Nothing beats a documentation. But it took me a few years to properly understand docs (I never actually tried to learn them tho)

rich adder
#

not even a documentation thing.. unity has thousands of videos in-house material

radiant sage
#

oh right I forgot

#

@slate helm forget what I said. Check the Unity videos, they are a really good resource

rich adder
#

they also been bumping their Youtube again with the newest unity 6 components

slate helm
#

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

radiant sage
#

If you dont want to do it

rich adder
slate helm
radiant sage
rich adder
#

I'd love to see it

slate helm
#

i made this but the rigging is hard

radiant sage
radiant sage
slate helm
radiant sage
#

not a fully fletched game

slate helm
#

exemple i can do modeling like fast i was able to make 3 weapon in the span of 45 min

radiant sage
#

I agree that a fully fletched RPG as a solo dev takes a few years

rich adder
#

your expectations might be too high

slate helm
#

but since i never touched coding like in C# idk how ti work

radiant sage
radiant sage
slate helm
#

and my ADD and ADHD dont really help with the focus and attnetion span so i need to also work on that

rich adder
#

start with simpler projects first, build up your knowledge

slate helm
#

what simple for beginner?

radiant sage
rich adder
#

flappy bird n such

radiant sage
#

with very simple graphics

slate helm
#

gotcha

rich adder
#

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

slate helm
#

i saw there was a editor tutorial in editor thingy in the website for when you in unity but how do i activate it?

radiant sage
#

they have tutorials for a variety of game types

slate helm
#

ye but i mean

rich adder
slate helm
radiant sage
#

exactly mate

slender nymph
# slate helm ye but i mean

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

slate helm
rich adder
#

yeah its true

#

there is a link

slate helm
#

oh

#

im so stupid i just saw it

#

told ya my focus suck

#

sorry

rich adder
#

after you finish the 1 step (installing unity ) it gives you the assets

slate helm
#

i have unity already installed

#

but im so confuse

#

i dont see the editor tutorial

slate helm
#

the pathway overview dont tell me

#

sorry...

rich adder
#

thats why its a structured course

#

you have to do the tasks, if you did already mark them completed and move on next

maiden relic
#

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.

rich adder
#

put the bool toggle in performed?

rich adder
maiden relic
#

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);
}

rich adder
maiden relic
#

Yea, I am working off starter assets input.

rich adder
#

btw you should mind as well take an Event approach instead of polling in update OpenInventory

maiden relic
#

yes you are right, what is the reason for that exactly? performance?

late burrow
#

how can i "set" how interface "get" gets its value

rich adder
grand snow
late burrow
#

how to setup interface at runtime

rich adder
maiden relic
#

okay thank you

slender nymph
grand snow
late burrow
#

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

grand snow
#

are you sure you mean interface?

slender nymph
late burrow
#

yeah property too many names there

dawn bolt
late burrow
#

oh so there is alternative of unityaction that can have return value

dawn bolt
#

mh

grand snow
solemn grotto
#

anyone know how to make a gun fire

rich ice
#

raycast

hot laurel
#

i was about to say american school kids for sure knows but raycast may be better response

wintry quarry
solemn grotto
#

i will watch tutorial

rich ice
#

i highly reccomend you go check !learn

eternal falconBOT
#

:teacher: Unity Learn โ†—

Over 750 hours of free live and on-demand learning content for all levels of experience!

void dawn
#

hey can someone help me

slender nymph
eternal falconBOT
#

: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

void dawn
#

unity wont let me use visual studio

#

it says i have to re install visual studio bu i already tried that

slender nymph
#

where do you see it telling you to reinstall it

void dawn
#

it appears a error message every time i try to open a script

slender nymph
#

show it

void dawn
#

its in Portuguese

slender nymph
#

and have you tried launching the visual studio installer to resolve whatever configuration problem there is?

void dawn
#

yeah , i will try again another time just to be sure

slender nymph
#

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

inland cobalt
#

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);
}```
slender nymph
#

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

cosmic dagger
inland cobalt
#

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!

summer nova
#

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 ๐Ÿ˜„

rich adder
#

why did you use MovePosition ?

summer nova
#

better use translate?

rich adder
#

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

summer nova
#

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);
rich adder
#

this is still wrong

#

you never want to use Translate with rigidbodies, you mind as well teleport its the same thing

summer nova
#

yep, know that

cosmic dagger
rich adder
#

just change it to do
Vector2 vel = new (xInput * speed, rigidbody2d.velocity);
rigidbody2d.velocity = vel

cosmic dagger
#

Especially, placing it in FixedUpdate . . .

eternal falconBOT
summer nova
queen adder
#

How can I change the sprite of a game object with a script.

rich adder
rich adder
#

make a field in the inspector if you want to assign a specific sprite

queen adder
#

okay.

rich adder
#

yeah unity 6+ and above

summer nova
rich adder
summer nova
#

oh, ok

#

I have to study that a bit more

queen adder
#

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");
        }
    }
}
rich adder
#

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

frigid sequoia
#

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?

rich adder
#

it only goes as far until it hits something

frigid sequoia
#

Like checking the whole line towards infinity

west radish
rich adder
#

nah it checks hit at the "tip" when something hits, it stops

west radish
#

And you can control how long the beam is

queen adder
frigid sequoia
#

But it doesn't find anything is just gonna keep checking up to infinte or what?

rich adder
queen adder
frigid sequoia
#

Doesn't that take like actally forever?

queen adder
west radish
#

As in the one that's on a game objects

cosmic dagger
rich adder
#

using strings is messy anyway. forget tags

west radish
#

@rich adder it'll make sense

rich adder
#

easier to just do
logic = FindFirstObjectByType<gameLogic>(FindObjectsInactive.Include)

rich adder
queen adder
#

no

west radish
#

drag the game logic gameobject into the field in the red green script

queen adder
#

okay

frigid sequoia
#

This is gonna return true if it does find the component, right?

timber tide
#

you dont need the generic parameters as it's implied in the out

void thicket
#

You don't need == true either

timber tide
#

it returns false if the component is not found

frigid sequoia
#

I thought it returned null

timber tide
#

and out would become null, so you can actually check either

void thicket
#

It returns bool

#

It's not possible to return null

cosmic dagger
#

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)
drifting cosmos
slender nymph
#

yes, every class, interface, enum, etc that you define in your code is a type

cosmic dagger
frigid sequoia
#

So this makes sense?

cosmic dagger
#

Basically, everything is a type . . .

slender nymph
#

yes, however you don't need to access the gameObject property on the collider to call TryGetComponent since it is also defined on Component

void thicket
#

You could also chain with &&

slender nymph
frigid sequoia
#

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?

void thicket
#

That's up to game logic

frigid sequoia
#

I mean like this

#

The mouse position uses a totally different metric from the world transform isn't it?

void thicket
#

You are not forced to use raycast

shrewd gazelle
#

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

slender nymph
#

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

frigid sequoia
void thicket
rich ice
obsidian granite
frigid sequoia
obsidian granite
subtle osprey
#

im trying to get a score system running and its not working

frigid sequoia
eager spindle
frigid sequoia
#

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

subtle osprey
frigid sequoia
#

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?

rocky canyon
#

no, you'd use translation

frigid sequoia
#

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???

north kiln
#

How are you debugging it? (I.e. what's the updated code?)

frigid sequoia
#

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

north kiln
wintry quarry
frigid sequoia
#

The second print is just not showing, si it's not detecting anything

wintry quarry
#

DrawLine expects two position vectors

north kiln
#

You should use DrawRay instead if you're passing a position and a direction

frigid sequoia
#

What's the difference?

north kiln
#

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

frigid sequoia
#

Welp, is doing exactly the same

#

Not detected

wintry quarry
#

What did you change and how

frigid sequoia
#

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

north kiln
#

Your layer is set to 0

#

which is not a LayerMask

frigid sequoia
#

It's not the default?

frigid sequoia
#

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?

north kiln
#

You're passing a layer into a parameter that expects a LayerMask

frigid sequoia
#

Cause I did at the start and didn't register either

#

Not detecting either

rich ice
#

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

frigid sequoia
#

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

rich ice
#

oh kk, just realised i've missed a lot in chat. gimme a bit to catch up

frigid sequoia
#

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

spark ember
#

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

rich ice
spark ember
cunning compass
#

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"?

rich adder
#

its got the same name as the method

#

thats a no-no

cunning compass
#

Ohh

#

I see

#

so do i change the class name?

rich adder
#

try to steer away from unity taken names lol

#

yea

cunning compass
#

ok

#

tysm

cosmic dagger
subtle osprey
#

eh? what am i doing wrong

cosmic dagger
subtle osprey
cosmic dagger
#

and it's post to post your !code for us to see. a small snippet doesn't help that much . . .

eternal falconBOT
cosmic dagger
north kiln
cosmic dagger
#

It's a difference between using an instance vs accessing the type . . .

cosmic dagger
subtle osprey
#

am i missing something or is this not the exact same thing?

#

OH

cosmic dagger
subtle osprey
#

OH MY GOD

#

i didnt capitalise the g

charred spoke
cosmic dagger
#

Take a closer look . . .

subtle osprey
#

i have been staring at this for 20 minutes

cosmic dagger
blazing ice
#

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

inland cobalt
#

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

inland cobalt
# rich adder

So do i need to define the logic to instantiate an object within my manager rather than my individual ObjectPool then?