#💻┃code-beginner

1 messages · Page 195 of 1

carmine sierra
#

then just access the variable

#

did everyone type at the same time or am i tripping

rich adder
#

You mean image?

summer stump
#

If you call get component on something not there, it will result in an error

spiral narwhal
#

A normal Unity sprite

summer stump
shell sorrel
spiral narwhal
#

Yes

shell sorrel
#

a sprite is jsut a asset

carmine sierra
rich adder
#

huh sprites dont block OnMouseEnter

carmine sierra
#

just not before the play test

summer stump
carmine sierra
#

okay cool thanks guys

shell sorrel
#

it wont block any of the event system events, unless you have a collider on it

rich adder
#

are you sure you dont mean Image component no UI

shell sorrel
#

also i would not use the old OnMouseEnter

rich adder
#

wait nvm im thinking of the IPointerEnter

#

OnMouseEnter only relies on colliders yes

spiral narwhal
#

I probably phrased it incorrectly: the issue is that the sprite is placed on top of another sprite as a sort of indicator icon. However, when hovering over the icon, that triggers OnMouseExit, basically "blocking" the raycast

rich adder
#

screenshot the object

#

are you sure you're not confusing it with UI

shell sorrel
#

also would not use the old OnMouse messages on mb but would use the IPointerEnterHandler

spiral narwhal
shell sorrel
#

takes a little more setup but offers more control

spiral narwhal
rich adder
spiral narwhal
rich adder
#

OnMouseEnter needs collider to work

spiral narwhal
rich adder
spiral narwhal
#

Oh it uses the green collider?

rich adder
#

yes

spiral narwhal
#

Ahhh

rich adder
#

If you want more control on what gets hit and when, I suggest doing your own Raycat

spiral narwhal
#

Can I use another collider as a trigger? How does Unity know which collider to use for OnMouseEnter?

rich adder
spiral narwhal
#

Called when the mouse enters the Collider. that's a terrible way to document the event method

#

What "Collider"?

#

What if there are multiple?

rich adder
#

the one on the script

shell sorrel
#

the collider on the same object as this script

rich adder
#

then both

spiral narwhal
#

Okay, so I can just use an additional and make it span the entire sprite for my issue to resolve?

#

And make it a trigger*

spiral narwhal
spiral narwhal
#

No, it seems to have ignored the second collider. I'm trying to give the indicator sprite a collider that outlines the actual object and give it the OnMouseEnter script right now

rich adder
spiral narwhal
#

Like this it now works as intended ^^ I just moved the collider to the Container object

#

Thank you for your help

tame mist
#

Hello, I'm trying to put a slider in my Options menu that allows the player to control the volume of a AudioMixer group called "mainVolume".
it seems to work in changing the values so that the things tied to the mainVolume group volume can be turned up or down. But the problem i'm having is when i reopen the Options menu the slider resets to it's min value which is 0.0001. in my observation of the Console tab it appears the SetSound Method gets called first and then the OpenOptionsMenu fires off. here is the code i have controlling it:

public void OpenOptionsMenu()
{
    float volumeValue;
    mainVolumeGroup.GetFloat("mainVolume", out volumeValue);
    mainVolumeSlider.value = volumeValue;
    Debug.Log("volumeValue = " + volumeValue);

    optionsMenuCanvas.SetActive(true);
    gameMenuCanvas.SetActive(false);
}

//this method is what the sliders OnValueChangedEvent calls dynamically  
public void SetSound(float soundLevel)
{
    //the fader value(-80db - 0db) is a logarithmic scale and the slider value is linear.
    //Instead of setting the slider min / max values to -80 and 0
    //(like you would to match the slider), set them to min 0.0001 and max 1.
    //Then in the script to set the value of the exposed parameter, use this to convert the linear value to an attenuation level
    Debug.Log("SetSound = " + Mathf.Log10(soundLevel) * 20);
    mainVolumeGroup.SetFloat("mainVolume", Mathf.Log10(soundLevel) * 20);
}
rich adder
shell sorrel
#

well you are setting it to the volume you got from the mixer group

#

which will be a negative value

#

do you already have it configured to support that, iirc out of the box the slider is clamped like 0 to 1 or something

tame mist
tame mist
tame mist
# shell sorrel which will be a negative value

yeah i think you're right it's getting a negative value so the slider defaults to the min.
based on the calculation i used to get the SetFloat value, how would i convert and set the proper value for the slider on the GetFloat of the mixer group?

shell sorrel
#

InverseLerp might help

#

will take your -80 to 0 value, and return you a 0 to 1 value based on where it lies in that range

tame mist
#

oh nice, thanks i'll check into it

shell sorrel
#

your SetSound what range is its soundLevel in?

rough valley
#

Hello Guys, I have a problem. I did a spawner for my CookieClicker Game and if I click the Cookie(Button) smaller Cookies spawn. The problem is the I can't see the cookies. I guess it have something to do with the layer. Can anyone help?

tame mist
polar acorn
#

Canvas objects shouldn't have SpriteRenderers

sour fulcrum
#

I want to remove / from a string but i don't know how to reference it in a way where c# doesn't assume im trying to do like a special character if that makes sense, trying to google it but getting poor results because its just ignoring the character in the search

polar acorn
sour fulcrum
#

oh neat

#

had no clue that was a thing

#

tyvm you two

rough valley
#

Don't look like its on a canvas

polar acorn
rough valley
#

This is the Button

polar acorn
#

Ah, okay.

#

It had the same name so I assumed it was that

rough valley
#

Is there a way to fix it? Or do I have to change the code

polar acorn
#

Where is the cookie sprite in relation to the camera?

rough valley
#

What do u mean?

polar acorn
#

Is the cookie sprite in view of the camera

rough valley
#

Yes

polar acorn
#

Show it, show a screenshot of your camera's view and what's in it

polar acorn
#

I don't know what's the camera and what's the canvas

#

and which direction the camera is facing

rough valley
#

big one is camera and smaller one is canvas

polar acorn
rough valley
#

they spawn at the top and fall down

polar acorn
rough valley
polar acorn
rough valley
polar acorn
#

It's on top of everything

#

the sprites are behind the canvas

rough valley
#

Okay thx. How can I change that?

polar acorn
#

You should probably use either UI or Sprite Renderers, not both

#

Your UI draws on top of everything

rough valley
#

If I use UI the cookies are invisible

tame mist
# shell sorrel InverseLerp might help

seems InverseLoop is really close but it's still a bit off. like the slider value will end up being a little bit higher to start, and then every time i close and reopen the Options menu it seems to go up a little each time.
this is the code i used in the OpenOptionsMenu method to get the slider value:
float i = Mathf.InverseLerp(-80, 0, volumeValue);

fickle stump
#

VR Question:
I wanna grab an object and as soon as i grab it, it's supposed to play a particle effect. I have the particle attached to the object, but i dont want to play it on awake.
So yeah question is: how do i activate particales after grabbing the parent object in vr?

rough valley
polar acorn
polar acorn
# rough valley

Having a collider and rigidbody means this probably shouldn't be UI, which means your background and whatnot also shouldn't be

rough valley
#

Hm I need the Collider to destroy the Cookies after they are out of the screen

#

Or how else can I do that?

#

@polar acorn

polar acorn
rough valley
#

I'm confused

#

Should I use UI or SpriteRenderer?

#

@polar acorn

#

Okay I don't need the collider for my cookie

rich adder
rough valley
#

So I would like to have "cookies" spawn over the screen and these should then fall down. They spawn over the screen but as soon as they reach the area where the background starts they disappear behind the background and only show up again as soon as the background is over. How do I fix this?

fickle stump
unreal imp
#

guys how i fix this? the code: LineRenderer tracer = Instantiate(tracerPrefab, muzzle.position, gunH.rotation); tracer.SetPosition(0, muzzle.position); tracer.SetPosition(1, hit.point); Destroy(tracer.gameObject, tracerDuration); the result:

tough lagoon
polar acorn
tough lagoon
unreal imp
fickle stump
#

that's gibberish to me XD

unreal imp
#

i think i know the problem

tough lagoon
# fickle stump i-- what? ._.

You can't change a bool directly through a Unity event. So you need to create a script that can do it with methods, and use those instead.

fickle stump
#

why is coding so hard

queen adder
#

It's not hard

#

It's just you missing experience and maybe motivation

#

🥰

warm depot
#

I accidentally created a memory leak but I'm not sure how to fix it. I know it's probably the while loop

#

but yea i basically want to move the cat towards a generated location

tough lagoon
warm depot
#

is there a way i can fix that

fickle stump
tough lagoon
#

Don't use a coroutine there

#

Mmm I see what you are trying to do

warm depot
#

what should I be using instead

#

I'm not sure how to set a delay within the while loop

tough lagoon
warm depot
#

roam is only ran once

#

with start

summer stump
tough lagoon
# warm depot roam is only ran once

So what I'd do is..

void Roam() {
  StopCoroutine(SlowMove());
  StartCoroutine(SlowMove());
}
IEnumerator SlowMove() {
  while ( wrong spot... )
  {
    ...moveTowards
    ...waitforseconds
  }
  Rest();
}```
faint sluice
#

@warm depot call while loop inside coroutine, because the way you have written it while loop is never going to exit and your program will crash

Inside coroutine do

While(condition)
{
Movetowards;
Wait 1 second;
}

Delay is arbitrary, put whatever you like

tough lagoon
#

Slow typing from my phone 😄

warm depot
#

oh ok so moving the while loop to the coroutine

faint sluice
#

Also if I'm not wrong doesn't movetowards require continuous update?

warm depot
#

yea

#

wait I only called the positions once so it was never going to break the loop

#

im dumb

faint sluice
#

Yeah so let's use yield return null instead of waitforseconds

tough lagoon
# warm depot oh ok so moving the while loop to the coroutine

Yeah because you want it to move over time and stop at the end.

It should be noted however you may want to give it a buffer. Getting spot on X and Y is sometimes hard. So try and let it get within like 0.1f of the range if that makes sense.

A good example I'd

if (Vector3.Distance(start, end) > 0.1f)
... move 
faint sluice
warm depot
#

ok thanks guys, I'll try that out

polar acorn
#

Remember that starting a coroutine does not pause anything. The code keeps right on trucking straight past it after starting it

#

that's what makes it "co" routine

warm depot
#

it works! 🙏

arctic ibex
#

So I've made an options menu, and one of the options is a resolution drop down. I set it up using a tutorial from Brackeys, but my resolutio isn't working. In unity, the game is the right aspect ratio, but for whatever reason when i export & run it, it's square? If I turn fullscreen mode on, it just streches the game to fix the whole screen instead of resizing.

#

Wait i forgot to attach the screenshots hang on

rough valley
#

Can someone help me? I tried to build my project for Android but it didnt worked. It just gave the error "* What went wrong:
Could not determine the dependencies of task ':unityLibrary:mobilenotifications.androidlib:compileReleaseJavaWithJavac'.

Failed to install the following Android SDK packages as some licences have not been accepted.
platforms;android-33 Android SDK Platform 33
To build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager.
Alternatively, to transfer the license agreements from one workstation to another, see http://d.android.com/r/studio-ui/export-licenses.html

Using Android SDK: C:\Program Files\Unity\Hub\Editor\2022.3.19f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights."
tepid summit
arctic ibex
unreal imp
#

How do I make it so that when it aligns well with the crosshair it changes its rotation and makes its forward the same as the crosshair's forward?

unreal imp
#

I say this taking as reference to the Team Fortress 2 team

tame mist
#

i'm using a UI Slider to adjust the volume of a AudioMixer group, I named the parameter "mainVolume".
the slider min is set to 0.0001 and the max is 1.
the math that was suggested to get the attenuation number between -80 and 0 is the following:
mainVolumeGroup.SetFloat("mainVolume", Mathf.Log10(soundLevel) * 20);
now when i get the number back from the AudioMixer group it's a negative number.
for example let's say it's -5.3, how would i covert it to be a percentage for the slider value to be between the 0.0001 and 1?

mild osprey
#

I know how to change it's position and make it move but would like to make it "loop" and come back after it gets to a certain point and restart

warm depot
#

is there a way I can shorten this? I feel like copy pasting practically the same code 4 times can be shortened somehow

#

i can replace the numbers at the bottom with beeCheck but the beeState1 and beeState2 are difficult

#

wait yea what am I talking about nvm

arctic ibex
#

Alright, so I've made a game, and it runs fine in the editor, but for some reason when I hit build & run, it becomes unplayable. It works, but the add force is really wierd, and is barely going faster then a drunken snail. Anyone know what could be causeing this?

ivory bobcat
arctic ibex
ivory bobcat
arctic ibex
ivory bobcat
#

Other concerns would be if this was a one shot of force being added (use impulse) and if this is occurring in fixed updated

arctic ibex
# ivory bobcat Use a larger value.

Did not solve the issue. It's also not just that it's too slow, but I don't keep any momentum once I deavtivate the Distancejoint (It's a grappling hook type swing mechanic)

ivory bobcat
arctic ibex
#

!code

eternal falconBOT
arctic ibex
#

here ya go

#

also don't mind me being bad at the game I made

ivory bobcat
arctic ibex
ivory bobcat
arctic ibex
ivory bobcat
#

Not sure what the logic behind checking if input was not zero then if input was one just to do a single task. Seems like AI generated or a bad tutorial.

arctic ibex
ivory bobcat
#

Where the first if statement is redundant. cs if not zero if one ...where you could have just usedcs if one ...

#

As one would certainly make it not zero already

arctic ibex
#

Then I would need another if statement anyway, cause I gotta check if it's -1 anyway

ivory bobcat
#

Looks like ai generated UnityChanHuh

arctic ibex
ivory bobcat
arctic ibex
#

I just used an if then an if/else instead of two ifs

ivory bobcat
#

Apply force in fixed update or use impulse force for single instances of additional force

arctic ibex
#

And what's the difference between update & fixed update?

ivory bobcat
#

Other than that, I'm not aware of how disabling a different component is having an effect on your object.

ivory bobcat
arctic ibex
ivory bobcat
arctic ibex
ivory bobcat
#

Cache input in Update and use the values in fixed update.

arctic ibex
#

oh okay

#

So have a bool set in update and reference it in fixed update?

ivory bobcat
#
private void Update()
{
    horizontal = Input.GetAxisRaw...
    vertical = Input.GetAxisRaw...
}``````cs
if(horizontal != 0)
    ...```
abstract finch
#

Is there a general rule to determine which variables come first? I.e. put spawnType before Room etc

eternal needle
# abstract finch ``` private SpawnInfo CreateSpawnInfo(Room room, Vector3 pos, SpawnType spawn...

not really, usually i go with an order that feels like it makes sense. Like would you want to tell the function to spawn a room, give it a position, then determine its spawn type? Or would you like to tell the function a room, give it a spawn type, then tell it the position? Usually id go with the 2nd option, but if you are using default params then you also must put those last
even though the order in this case doesnt affect anything, it would feel weird if one function took a position then rotation, while a different function took a rotation then position

mild osprey
glass crest
#

Good morning, what does the term "Op" in "OpCreateRoom" means in photon?

abstract finch
eternal needle
eternal needle
#

i do usually put my custom classes before the structs, so stuff like Vector3, Quaternion, etc, go last but thats just what feels right to me

#

because the classes are usually more important

eternal needle
#

its probably "operation" but thats just a guess

lyric pond
#

Does the first person unity starter asset not come with the audio setup for footsteps anymore?

glass crest
eternal needle
glass crest
hazy crypt
#

Good morning guys, is anyone available to help me understand some rigid body forces?

faint osprey
#

ok so my level is a procedurally generated dungeon and when i reach the end of the current dungeon floor i want the player to be taken to the next floor of the dungeon which has the exact same as the first just harder enemies so how do i like reset a scene almost but keeping some values in scripts continued between levels

rare basin
#

dont ask to ask

hazy crypt
#

I see

#

I want to recreate the movement from an old project but I don’t know how it was done before

#

I mostly worked on level design and stuff and my friend worked on the scripting

#

But now the game has been dead for time and I’d like to revive it

#

Here’s the gameplay

sick charm
#

Hi how to add jump animation for character using kinematic character controller(unity assest store) as it doesnt detect isGrounded

rare basin
#

whenever you jump, trigger the jump animation

sick charm
#

I used a asset store add on kinematic character contoller which has slope check rather than ground check for jump action , so if i trigger a jump animation it just plays and doesn’t return to walk animation after landing

rare basin
#

then make ground check system yourself

sick charm
#

Ohh will try

tepid summit
#

private void = !public void

#

in a way

rare basin
#

that wont even compile

#

that line doesn't make any sense

eternal needle
#

There is more than just public and private

visual hedge
tepid summit
#

dw

#

its 9pm

#

this is 9pm Dark

#

nice to meet you

visual hedge
#

or is it 9pm high? looks like it

tepid summit
#

all of the above

tepid summit
icy junco
#

is it interesting to still work with the unity version 2021

#

or 2020

keen dew
#

Depends what you find interesting I guess

queen adder
#

Anyone managed to make a savesystem for delegates before? For delegates with lambda registers?

rare basin
#

a saveystem for delegates?

#

what do you mean

queen adder
#

like ```cs
public Action acti;

void Update()
{
if("x".IsPressed())
{
acti += () => {Debug.Log("message");};
}
}```

#

then save acti and when you reload, load then invoke it, it will log the message next time

rare basin
#

then...

#

dont make it anonymous functions?

queen adder
#

they are anonymous function

#

the reason i was asking

bright zodiac
queen adder
bright zodiac
#

yeah, that's why they deprecated BF due to how it full of security holes in it

#

no they don't

queen adder
#

security holes? like dangerous for users(players)?

bright zodiac
#

yeah

#

it's a known issue in c# world for years

rare basin
#

if you are using BF - stop immediately

queen adder
#

actually yea, being able to play with delegates alone sounds trick for players

rare basin
keen dew
#

Imagine if you went on to load delegates from the save file. Nothing would stop someone to edit the save file so that the delegate would format your hard drive instead or whatever they wanted

rare basin
queen adder
#

so for my case, my best approach is to like turn them into methods and save a reference to my methods then launch a reflection?

bright zodiac
#

you're trying to seriliaze a delegate is just wrong in many ways

keen dew
#

Put your delegates in a dictionary, save the dictionary key instead

queen adder
#

that can work yea, but ig, id have to like a persistent large dictionary

#

but yea, ig that's best for now

modest dust
#

It's always fine to dm me and ask stuff as long as the question is reasonable. But generally research and asking your question here should come first. And from what I could see from your few next messages you might be missing a few C# basics, so you should learn these first if you don't fully understand them yet

hazy crypt
#

Hey guys, did anyone get a chance to see my messages above?

#

I’d really appreciate a hand understanding this

#

I’ve spent maybe 6 hours experimenting with very little results and I feel like I’m hitting my head against a wall lol

queen adder
#

that's not your game?

hazy crypt
#

Yes it is

#

Or it was

#

4 years ago

#

The project is gone now but I was lead level designer

#

The other guy did all the scripting but it was just the two of us

#

I want to revive it but I need to learn how to do his side of the project lol

queen adder
#

there's no version control?

hazy crypt
#

It’s gone gone, no backups or anything

#

I have to start from scratch

#

I’ve had three different computers and a new Unity account since then

#

The other guy that I worked with is too busy and doesn’t want to remake it

#

He too has lost all the project history

#

It wasn’t too deep a concept though, if I can get the player character rolling properly I can sort of find my way from there

rare basin
#

people divide into 2 groups

#

these who is making backup

#

and these who will be making backup

timid saffron
#

@hazy cryptI am using this script they shared in resources I recommend

hazy crypt
#

I will use it now yeah

trail heart
hazy crypt
#

I only had his phone number and he no longer responds

#

We haven’t spoken for years

eternal needle
#

From the video, it doesnt look too complicated. Most of it can be done easily via rigidbody movement but youd have to setup physics materials for that bouncy interaction.

rare basin
#

looks like normal, velocity based player controller

#

with bounciness material on it

#

nothing fancy

hazy crypt
#

All I’m really interested in is the rigid body movement for now, the extra bouncy and weird interactions I can fuck with late

#

I’ve tried adding forces globally and relatively, and I’ve tried constraining movements but I can’t ever quite get it to work

rare basin
#

how much are you familiar with Unity

#

are you a begginer?

hazy crypt
#

I’m fairly new yeah

rare basin
#

then you should watch some tutorials on physics based movements

queen adder
#

but you can make maps in editor?

hazy crypt
#

I’m new to scripting but I’ve done maybe 100 hours of level design

#

Working with blender, probuilder, Krita etc

#

I’ve done a little shadergraph stuff too

#

But C# is new to me

rare basin
#

step by step

eternal needle
#

if you have no background in coding, you'll either want to start with basic c# or find someone else to do the coding for you.

rare basin
#

learn basics c#, then learn rigidbodies etc

hazy crypt
#

I am fairly proficient in HTML and Python

#

Code in general is not new to me, just C#

#

I can work my way around it, like I said I’ve been experimenting in C# to try to get this to work

#

I’m happy to use the Unity docs which are great

#

But you guys have a ton more experience so I was hoping someone would see my video and say “that’s how it’s done”

rare basin
#

yes, we did

#

it's done through rigidbody

#

with bouncy physics materiall

hazy crypt
#

Yes I have a rigid body setup

#

And I’m adding torque forces

rare basin
#

there is no magic formula

#

or magic code

#

that recreates this movement

eternal needle
#

For actual help then you'll need to share more of what's actually not working and the code. Theres really no way to say what the person did. It could be rigidbody, it could be a custom character controller that's made pretty well to look like physics.

rare basin
#

try&error process

hazy crypt
#

No no I’m not asking for magic, that’s silly

eternal needle
#

Torque is also for rotation

rare basin
#

start experimenting, play around with rigidbody and differet movement approaches

#

and see what looks most familiar

keen dew
#

Based on the video it doesn't look like it's using torque/rotation to move

hazy crypt
#

Perhaps it’s just adding a force?

queen adder
keen dew
#

Even visually it's using thrusters to move

hazy crypt
keen dew
#

If it rolls at all it's a side effect, not the moving force

hazy crypt
#

The thrusters that is

eternal needle
keen dew
#

yeah but it changes direction in the air, that's not torque

queen adder
#

actually, ig the rotation is just a side effect of friction

queen adder
#

it's not applying torque to move

hazy crypt
#

I hadn’t thought of this

#

Okay so there’s a local forward force for the drive

#

Then there’s a rotation around the Y axis to change direction

keen dew
#

My advice would be to forget about rotation and just apply directional forces

hazy crypt
#

How would I go about that

keen dew
#

AddForce(direction)

hazy crypt
#

I recall that if the ball is sat still, you can still turn it around

#

Can I achieve that in the same way?

#

The thrusters and camera would rotate around the ball to face the new forward direction

#

Perhaps the ball didn’t rotate

keen dew
#

Rotating the ball for steering is a different thing from moving it

hazy crypt
#

I see

#

I have an idea about how I can make this work now

#

Thank you all very much for your help

faint osprey
#

when i reload a scene is it only static varaibles that arent reset

lean basin
#

Quaternion.LookRotation is used to convert Vector3 direction to Quaternion rotation. But what about the opposite of that operation?
How do I convert Quaternion to Vector3 direction (not euler angle)?

queen adder
#

or was it up

#

just try both

rough dust
#

Not sure if this is a question for #💻┃code-beginner or somewhere else, but I have a map panel, that houses my panel scroll rect as my map panel so the player can see where their ship is. And I'm attempting to make a button that moves the map, or my game object called "Panel" so the ship UI image is centered within the scroll rect. But with my current function, it doesn't seem to work. I've been wrestling with this for an hour and I don't know what to do

public void CenterShip()
    {
        // Get the size of the scroll rect
        Vector2 scrollRectSize = mapPanel.parent.GetComponent<RectTransform>().rect.size;

        // Calculate the center of the visible area of the scroll rect
        Vector2 scrollRectCenter = new Vector2(scrollRectSize.x / 2f, scrollRectSize.y / 2f);

        // Calculate the ship's anchored position relative to the center of the map panel
        Vector2 shipPositionRelativeToCenter = shipImage.rectTransform.anchoredPosition - mapPanel.anchoredPosition;

        // Calculate the difference needed to center the ship
        Vector2 difference = scrollRectCenter - shipPositionRelativeToCenter;

        // Move the map panel by the difference to center the ship
        mapPanel.anchoredPosition += difference;
    }
queen adder
#

if you press the button, you want the scrollrect to center on the ship?

rough dust
lean basin
queen adder
#

idk how you ship is setup there, but you need to figure out how many percentage it is from bottom left to top right

#

if it is in the very center, set this normalizedPosition to (0.5, 0,5)

rough dust
#

This works to center the scroll rect on the middle of my map panel which might actually come in handy later on, but right now I'm trying to center the scroll rect on the ship image. Which moves around within the map panel. That's what I can't figure out.
I need something that is able to calculate how far to move the my map panel so the ship is in the center.

#

Not even ChatGPT knows how to help XD so I'm completely lost lol

frosty hound
#

Not even? Must be unsolvable then if not even chatGpt can solve it!

rare basin
#

hmm if chatgpt doesnt know the answer

#

then i think it's just impossible to do it

queen adder
#

anyways, you just missing the math part, you can solve it by using Mathf.InverseLerp new Vector2(Mathf.InverseLerp(botlef.x, topright.x, ship.position), Mathf.InverseLerp(botlef.y, topright.y, ship.position))

#

botlef and top right are the edges

#

u figure out how to get their positions

hidden sleet
#

How does OnMouseDown work when you have an empty parent with child objects, but you want the parent to move? Would clicking on the children fire their own OnMouseDowns and not do the parent's one? I've only got a script on the parent but it's not working as I'd hoped

carmine sierra
#

how can I fix a nullreferenceexception error here? the issue is weaponinstance spawns later in the game

carmine sierra
queen adder
#

you can delay it by turning your start into a coroutine, but that's ugly fix

rare basin
#

that's not a good idea

#

why are you putting this in Start() (thats called only once)

carmine sierra
#

i said weaponinstance cannot be null though

queen adder
#

hence why im asking why is the weapon late to begin with

carmine sierra
rare basin
#

that was a question but ok 😄

carmine sierra
#

so should I make a function which has the if statement

carmine sierra
#

so if I make it an update it should work

rare basin
#

just dont use it in Start() if you dont want it to trigger on Start

carmine sierra
#

would it take up memory

#

i will only be checking for that one line every frame

rare basin
#

but that is entirely wrong what you are trying to do

carmine sierra
#

yeah I didn't realise just use start to initialise every variable

#

how comes

rare basin
#

just grab the references

#

whenever you spawn the weaponInstance

#

when the weaponInstance is not null

carmine sierra
#

yeah so I should just make start any other function?

rare basin
carmine sierra
#

doing it

hidden sleet
#

Yeah this is odd, for some reason my OnMouseDown is just never fired now :/

#

Got this setup, the positionMover has a mesh collider and a script that changes it's position as follows.
But it simply doesn't let me drag, and there aren't any errors either. That 'clicked' debug log simply never shows

    public Camera camera;    

    private Vector3 offset;

    private Plane dragPlane;

    private void Start()
    {
        //Creates a plane to lock movement to
            
        
            dragPlane = new Plane(Vector3.up, transform.position);
        
        
    }

    private void Awake()
    {
        camera = GameObject.Find("Camera").GetComponent<Camera>();
    }

    private void OnMouseDown()
    {
        Debug.Log("Clicked");
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        float enter = 0.0f;

        //Perform a raycast and return true if it intersecets the defined plane
        //The offset is used so that you can grab the edge of an object
        //and the object won't snap to where the mouse is
        if (dragPlane.Raycast(ray, out enter))
        {
            offset = transform.position - ray.GetPoint(enter);
        }

    }


    private void OnMouseDrag()
    {

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        float enter = 0.0f;

        //Perform a raycast from the camera to this invisible plane
        //If the raycase hits, return the distance of the cast from the origin
        //Set the updates position of the object to where the mouse is on the
        //plane plus the initially defined offset, but ignore the y axis.
        if (dragPlane.Raycast(ray, out enter))
        {
            Vector3 newPosition = ray.GetPoint(enter) + offset;
            transform.position = newPosition;
            Debug.Log("Moved Position");
        }
    }

}```
rare basin
#

dont use OnMouseDrag/Enter/Exit

#

use IPointerEnterHandler etc instead

hidden sleet
#

I'll have to look into those ones then

#

this is very rough as I'm still starting out

#

but it worked fine earlier, it only broke after adding the cinemachine which doesn't make sense to me

carmine sierra
#

what could be wrong now?

#

chatgpt aint helping

earnest atlas
#

is weapon instance a singleton static ?

carmine sierra
#

i dont know what that is

earnest atlas
#

its means it not then

carmine sierra
#

its just an instance of a prefab

earnest atlas
#

you can initialize it

#

if its prefab just add it as thjat

carmine sierra
#

but if it isn't being spawned in this code

#

then wouldn't that be an issue

earnest atlas
#

[SerializeField] private GameObject _weaponSpawn ;

#

Where is it spawned then?

carmine sierra
#

in another script weaponspawn

#

thats what I reference at the top

earnest atlas
#

is "THIS" script in the same object as weaponSpawn?

#

or in different?

carmine sierra
#

different

earnest atlas
#

is that different object not a child or parent of this object?

#

just screenshot me

#

I cant guess

carmine sierra
#

no

#

cannonball shop is the parent of weaponspawn

#

wont let me send an image

earnest atlas
#

its same 3 screenshot

carmine sierra
earnest atlas
#

open you cannonball object

#

now we have 4 images

carmine sierra
#

mb my wifi or something

earnest atlas
#

why u have object called weapon list?

carmine sierra
#

its an empty object for later

#

when I add more weapons

earnest atlas
#

Whatever

#

Open the cannonbal

#

I still dont understand where your scripts are positioned

carmine sierra
earnest atlas
#

and as I would belive chatgpt made you create lots of classes

#

I mean open its children

#

the arrow on the left

carmine sierra
#

cannonballs children

#

there are none

earnest atlas
#

Where is script you are using

carmine sierra
#

idk if the image sent my wifi is bad

#

but only the parent objects hold the script

#

the children are aesthetic only

earnest atlas
#

You can to access that script do so far 3 things

#

serialize it

#

find it

#

store it somewhere and access it like that

carmine sierra
#

what should I do that for sorry?

earnest atlas
#

[SerializeField] private GameObject ObjectUWannSerialize;

#

Other solution is GameObject.Find()

carmine sierra
#

why would I want to serialize it

earnest atlas
#

TO acess the script

carmine sierra
#

the weaponspawn one right

earnest atlas
#

Cause you can later just do GameObjectYouWannaFind.GetComponent<ScriptWhateverName>();

#

Find object is evil

#

Better used with findbytag

#

I wrote it wrong I know I just dont remembe how was it

carmine sierra
#

so this line alone doesn't reference the script of the name WeaponSpawn?

hexed terrace
#

it isn't assigned anything

earnest atlas
#

If you dont need separate completly objects you can just make so they have same parent and just climb it like that

carmine sierra
#

ohh alr

earnest atlas
#

No, its just creating a variable with its reference

carmine sierra
#

would i keep that line and then find the object

earnest atlas
#

Finding objects is bad

carmine sierra
#

in a function like start

earnest atlas
#

Just serialize the other object that has that script

#

and get the components out of it into that variable u have

#

btw my own question.

if you get transform.parent then search inside that object for a child with a name. Is it bad as GameObject.Find or not?

Im mostly using it for not serializing objects on each different scene when I want to get scene objet

hexed terrace
#

"NEVER" search by name, string searches are slow and prone to human error

earnest atlas
#

So how to get a child I want then?

hexed terrace
#
  • manually assign in the inspector
  • use GetComponentInChildren<T>() / GetComponentsInChildren<T>()
earnest atlas
#

yeah thats so far what I did

hidden sleet
#

How else would you do it? For instance in one of my scripts I access the main camera that has a custom name. ```cs
public CinemachineFreeLook freelookCamera;
private bool rotationEnabled = true;

private void Awake()
{
freelookCamera = GameObject.Find("FreeLook Camera").GetComponent<CinemachineFreeLook>();
}``` But since it's a prefab I thought I had to find the component when it appears

earnest atlas
#

Serialize it

#

Its a camera

hexed terrace
#

Either expose to the inspector and manually assign it, or FindObjectOfType<CinemachineFreeLook>();

hidden sleet
#

Can I just drag stuff from scenes onto prefabs anyways?

hexed terrace
#

oh a prefab, no

#

you can't have scene references on a prefab - in the project folder, an instance of a prefab can obvs have references to scene objects

earnest atlas
#

Yeah because that will work in the most weird manner

hidden sleet
#

Cause this is supposed to appear on a prefab, so I don't know any other ways to get the camera from the scene it spawns in

earnest atlas
#

Well you can store reference somewhere else

hidden sleet
#

And that's just better outright than a string search?

hexed terrace
#

of the thing that spawns it gives it the required references

earnest atlas
#

wdym expose to inspector?

hexed terrace
earnest atlas
hexed terrace
#

public/ [SerializeField]

earnest atlas
#

and pass it in that same moment

hexed terrace
#

fields sholdn't ever be public though, so SF is the way

earnest atlas
hexed terrace
#

🤔

earnest atlas
hexed terrace
#

object = otherObject;

earnest atlas
#

You cant pass a prefab object from scene

hidden sleet
#

So if you've got a whole heap of cameras, is it generally better to just hold a list of cameras somewhere and get that one from a list so you can avoid string searches

earnest atlas
#

I mean you create object and want to tell that object "here have this reference:

timber comet
earnest atlas
#

yes

#

Im constantly forgetting names

timber comet
#

Just do Gameobject gm = Instantiate(…)

#

In the instantiate put your prefab gameobject

hexed terrace
timber comet
#

And now you have a reference to the spawned object

earnest atlas
#

I have this in player to pass references to the GameController instance

#

This are the values

#

How else would you pass it there?

#

This script allows me to not bother running that multiplle times and on scene load it will run without issues

timber comet
#

Is the PlayerController script attached to the player GameObject?

earnest atlas
#

playercontroller is Static Singleton

#

So I can acces its values ;like that

#

How would you pass the references to the scripts?

timber comet
earnest atlas
#

and call it to set the object?

timber comet
#

And then reference it through the instance

timber comet
earnest atlas
#

But I also want to be able to get access to those values

#

In different scripts

#

I have this for score

#

its for not updating UI constantly

timber comet
earnest atlas
#

yeah I dont see how I can make it protected like private and also be able to access it from elsewhere

timber comet
#

The current code is just fine, you can access your variables through the instance

timber comet
#

Just do a get and private set

timber comet
hidden sleet
#

Do Plane raycasts not have a way to avoid specific layers?

timber comet
hidden sleet
#

That's what I'm trying to figure out

#

but I can't see a method overload that includes a way to ignore a certain layer

timber comet
# hidden sleet but I can't see a method overload that includes a way to ignore a certain layer
hidden sleet
#

doesn't seem to work with Planes

#

there isn't an overload that can take those arguments

#

Cause I've got a plane so it can only move said object on the z and x axes - private Plane dragPlane; But It keeps hitting the wrong collider when I cast it if (dragPlane.Raycast(ray, out enter)) { offset = transform.parent.position - ray.GetPoint(enter); }

earnest atlas
#

Im pretty sure raycast only works with layers?

earnest atlas
#

So back to square 1

timber comet
#

Make a public void

faint sluice
timber comet
hidden sleet
rare basin
#

pick one

timber comet
#

If you make a public void and pass variables from there

timber comet
timber comet
rare basin
faint sluice
timber comet
rare basin
#

that's what i said

timber comet
#

Unless

hidden sleet
#

yes, and that doesn't solve it. That overload only exists for Physics.Raycast, not Plane.Raycast, which is what I showed in my code snippet

timber comet
#

You can reference a void

#

And pass the variable there

timber comet
hidden sleet
#

np, I think I may Just need to switch to Physics raycast but then find another way to replicate this behaviour

#

Would it be stupid to cast a ray onto the plane, then cast another ray to that point so I can then check it's layer?

earnest atlas
#

wdym?

hidden sleet
#

Well i've got this larger trigger collider surrounding my capsule which is larger than the custom movement gizmo that I want to be able to click and drag to move around, but I can't click it since it's encompassed by that trigger. And clicking on that larger one ends up running my OnMouseDown method, which isn't ideal.

#

I think I may just need to rethink how I do click detection and not use onMouseDown as you said

earnest atlas
#

This what raycast with filter to layer will do

hidden sleet
#

So I was thinking about instead firing a ray on the onmousedown and use that to check the layer before then

hidden sleet
#

I think I'm not explaining my situation as well as I could.

#

I'll go and see if this idea of mine works and I'll come back with a better explanation if it doesn't

#

wait hang on, these layer overrides in the collider, can that give a collider a specific layer if the object itself belongs to another?

thick shadow
#

is there someone that can help me with a small camera code thing?

hidden sleet
dense cypress
#

getting this error when making a build

Unable to find player assembly: Library/PlayerScriptAssemblies/UnityEngine.TestRunner.dll
UnityEngine.Debug:LogWarning (object)
Unity.Burst.Editor.BurstAotCompiler:OnPostBuildPlayerScriptDLLsImpl (Unity.Burst.Editor.BurstAotCompiler/BurstAOTSettings,UnityEditor.Compilation.Assembly[]) (at Library/PackageCache/com.unity.burst@1.8.11/Editor/BurstAotCompiler.cs:654)
Unity.Burst.Editor.BurstAOTCompilerPostprocessor:DoGenerate (UnityEditor.Compilation.Assembly[]) (at Library/PackageCache/com.unity.burst@1.8.11/Editor/BurstAotCompiler.cs:330)
Unity.Burst.Editor.BurstAOTCompilerPostprocessor:OnPostBuildPlayerScriptDLLs (UnityEditor.Build.Reporting.BuildReport) (at Library/PackageCache/com.unity.burst@1.8.11/Editor/BurstAotCompiler.cs:199)
UnityEditor.EditorApplication:Internal_CallGlobalEventHandler ()

thick shadow
earnest atlas
#

small camera code thing 😄

thick shadow
#

what i want is that the camera followes the player. but rotates around it smoothly. but what it does now is just rotating around it really freaking fast. and not smooth. even after edjusting the smooth rotation in the inspector. here is the code:
Dont mind the language after the //'s that dutch so i understand better XD

using UnityEngine;

public class CameraFollow : MonoBehaviour
{
public Transform target; // De transform van de speler om te volgen
public float rotationSpeed = 5f; // De snelheid waarmee de camera om de speler heen draait

private Vector3 offset; // De offset van de camera vanaf het target

void Start()
{
    // Bereken de offset van de camera ten opzichte van de speler
    if (target != null)
    {
        offset = transform.position - target.position;
    }
}

void LateUpdate()
{
    // Controleer of er een speler is om te volgen
    if (target != null)
    {
        // Bereken de rotatie om de speler heen
        Quaternion targetRotation = Quaternion.Euler(0f, target.eulerAngles.y, 0f); // Draaien om de y-as van de speler

        // Roteer de offset van de camera
        offset = targetRotation * offset;

        // Bereken de gewenste positie van de camera
        Vector3 desiredPosition = target.position + offset;

        // Stel de positie van de camera in op de gewenste positie
        transform.position = desiredPosition;

        // Kijk altijd naar de speler
        transform.LookAt(target.position);
    }
}

}
using UnityEngine;

public class CameraFollow : MonoBehaviour
{
public Transform target; // De transform van de speler om te volgen
public float rotationSpeed = 5f; // De snelheid waarmee de camera om de speler heen draait

private Vector3 offset; // De offset van de camera vanaf het target

void Start()
{
    // Bereken de offset van de camera ten opzichte van de speler
    if (target != null)
    {
        offset = transform.position - target.position;
    }
}

void LateUpdate()
{
    // Controleer of er een speler is om te volgen
    if (target != null)
    {
        // Bereken de rotatie om de speler heen
        Quaternion targetRotation = Quaternion.Euler(0f, target.eulerAngles.y, 0f); // Draaien om de y-as van de speler

        // Roteer de offset van de camera
        offset = targetRotation * offset;

        // Bereken de gewenste positie van de camera
        Vector3 desiredPosition = target.position + offset;

        // Stel de positie van de camera in op de gewenste positie
        transform.position = desiredPosition;

        // Kijk altijd naar de speler
        transform.LookAt(target.position);
    }
}

}

earnest atlas
#

!code

eternal falconBOT
languid spire
#

AI Code

rare basin
#

jezus another chatgpt enjoyer

languid spire
#

And in Dutch as well

rare basin
#

🥶

earnest atlas
#

After dealing with chatgpt as much as I normally do you can recognize AI text easy. It loves one specific sentence strucuting so much

thick shadow
languid spire
#

AI Code is not allowed here

earnest atlas
#

Sphere cast is same raycasthit?

gaunt ice
#

the "return struct" are the same

hexed terrace
scarlet skiff
#
if (Input.GetMouseButtonUp(0) && (reload.reloadBar.value >= 0.2f) && !reload.isReloading && canShoot)
{
    Debug.Log("here");
    float chargingTime = Time.time - timeWhenCharge;
    Jump(chargingTime, reload.reloadBar.value);
}

Why wont the if statement happen even when all the condition are true, sometimes it bugs out and still wont play whats inside the if loop, this happens if you charge a jump to power = 4

Jump code: https://gdl.space/uxuxotukuk.cs
Reload code: https://gdl.space/ihobitukez.cs

thick shadow
scarlet skiff
#

i can jump 5 tiems before relaoding if they all are power 1, but if i do one with power 4, id still lose out on 1 jump on power 1

rare basin
scarlet skiff
#

run time

gaunt ice
#

have you logged >=0.2f?
dont trust the value you see in inspector

#

1.9999999 is 0.2 but it is <0.2

scarlet skiff
#

bruh reload.reloadBar.value >= 0.2f was the problem 😡

#

stupid inspector

#

how would it not become 0.2 tho

stuck palm
#

i've had this bug for ages now where all my code is telling me that a particle system is emitting, but I can't see it in the editor. this code runs in update, and the console is telling me that its workuing normally, but i cant see anything unless i explicitly click on the player in the hierarchy for some reason. (false was when the player just got spawned)

if (movement.magnitude > 0.6f) 
        {
            
            sprintPuffs.Play();  
        }
        else
        {
            sprintPuffs.Stop();
        }
        print(sprintPuffs.isEmitting);
#

you cant see the sprint particles being spawned behind the player

scarlet skiff
night mural
night mural
#

does it work fine when you are actually playing the game?

scarlet skiff
hexed terrace
#

You want !reload.isReloading to log out false

stuck palm
#

pause just stops them in place

carmine sierra
#

im trying to reference an instance which is instantiated in the script 'weaponSpawn' but get a nullreferenceexception

hexed terrace
#

Shop is of type GameObject

carmine sierra
#

yeah its not a gui

hexed terrace
#

what

carmine sierra
#

its a gameobject

hexed terrace
#

so you can't do .weaponInstance on it..

carmine sierra
#

ohh your right

night mural
hexed terrace
#

weaponSpawn also doesn't exist? at least you're not showing it in the screenshot

night mural
carmine sierra
#

okay testing the changes now

stuck palm
night mural
#

i think you meant to set weaponSpawn in Start but instead you just read something and move on

timid saffron
#

this script works either way. whats the point of destroy(other.gameobject)

stuck palm
#

the magnitude is consistent

hexed terrace
shell sorrel
night mural
timid saffron
shell sorrel
stuck palm
carmine sierra
#

I have a new bug which i think appears here, weaponinstance is a instance which is saved in another script as a public variable. does the line 'weaponInstance.transform.position = nowPos'; reference the actual object of the instance? cause if not I dont know how to reference the actual object

night mural
frigid sequoia
#

Ey, a quick here, can I make like a expandible header for inspector fields?

polar acorn
polar acorn
frigid sequoia
#

Like lets say I want the header of Debug fields so it can be toggle to expand and show fully

#

Ok

stuck palm
merry harness
#

how do i rotate a prefab? im making a flappy bird clone as my first project but everytime i make the pipes a prefab they are on their side instead of the correct way

#

looked through the internet but cant find anything useful

night mural
eternal falconBOT
rare basin
#

define right

night mural
carmine sierra
# rare basin define right

would weaponinstance.transform.position refer to the actual weapon instance object or just that public variable in the code which refers to the instance

hexed terrace
rare basin
#

recording tools exists you know

frosty hound
#

@timid saffron Don't record on your phone. Use a screenshot or something like OBS.

timid saffron
hexed terrace
#

get one, takes 2 mins

rough dust
#
    public void CenterShip()
    {
        RectTransform mapRectTransform = mapPanel.GetComponent<RectTransform>();

        // bottomLeft corner of MapPanel
        Vector2 bottomLeft = mapRectTransform.anchoredPosition - mapRectTransform.sizeDelta / 2f;

        // topRight corner of MapPanel
        Vector2 topRight = mapRectTransform.anchoredPosition + mapRectTransform.sizeDelta / 2f;

        // Ship's position relative to corners
        Vector2 shipPositionRelativeToCorners = new Vector2(
            Mathf.InverseLerp(bottomLeft.x, topRight.x, shipImage.rectTransform.position.x),
            Mathf.InverseLerp(bottomLeft.y, topRight.y, shipImage.rectTransform.position.y)
        );
        Debug.Log($"AnchoredPosition: {mapRectTransform.anchoredPosition}\nBottomLeft: {bottomLeft}\nTopRight: {topRight}\nShipPositionRelativeToCorners: {shipPositionRelativeToCorners}");

        // Set normalized position
        scrollRect.normalizedPosition = shipPositionRelativeToCorners;
    }

This is my function to at least ATTEMPT to position my map panel so my ship image is centered within my scroll rect. But I just can't figure out why it doesn't seem to work. When I center it, it's about 300 pixels too far in the negative Y, and also the mapRectTransform.achoredPosition keeps changing in value, isn't the anchored position supposed to... not change?

frosty hound
hexed terrace
#

something like ShareX is better for quick screengrabs

rare basin
merry harness
timid saffron
#

well forget about the video anyway. it was just to show that I saved

late bobcat
#
 private void OnTriggerStay2D(Collider2D collision)
 {
     
     if (collision.gameObject.CompareTag("Enemy") && _canBeHit == true)
     { 
             if (PHealth >= 10)
             {
                 PHealth -= 10;
                 healthbar.SetHealth(PHealth);
                 StartCoroutine(InvulnerabilityCD());
             }  
     }
 }

Hey there guys, i've a question. I've a laser beam gameobject coming out of my player's Head. I attached the player gameobject to the player's head and the player's Head is attached to the player gameobject. I had to make it like that so the laser could follow along the walking, idle animations of the player. But now i've a problem. Since laser is a child of the player's gameobject my player model takes damage when i hit enemies with laser because of the snippet i've attached to this message. How can i modify the provided snippet in order to make it so: Laser is still attached to the player gameobject's head and player doesn't take damage if laser collides with enemy?

hexed terrace
#

why does the player have an EnemiesHealthSystem component?

late bobcat
#

I can provide hierarchy screenshot if needed

hexed terrace
#

What's PHealth and healthbar ?

#

Looks like you're doing player health things and enemy health things in the same class, when you shouldn't

late bobcat
#

Phealt = player healt, healtbar is just healtbar gameobject that updates when enemies collides with player

night mural
late bobcat
#

idk why it copyed it

polar acorn
hexed terrace
#

What gameobject is this code on?

night mural
#

everyone knows the player is the enemy catsmart

late bobcat
#

that should check if player collided with enemy, if so it makes Player health decrease by 10

late bobcat
hexed terrace
#

so then your laser is tagged as enemy

timid saffron
merry harness
night mural
merry harness
late bobcat
night mural
#

well go do some basic unity tutorials and you'll get there

merry harness
#

my prefab has 2 parts, one is a parent, one is a child of the parent

late bobcat
merry harness
#

and i cant find anything on this

night mural
merry harness
#

can you check my dm?

stuck palm
hexed terrace
eternal falconBOT
night mural
# merry harness can you check my dm?

this tutorial explains the method https://www.youtube.com/watch?v=NsUJDqEY8tE

🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
Let's learn how the Game Object Transform Pivot works and how we can manipulate it to get it working exactly as we want.

If you have any questions post them in the comments and I'll do my best to answer them.

See y...

▶ Play video
river glade
#

Hi everyone, sorry, it's the first time I've come across these errors, how can I resolve it?

night mural
stuck palm
night mural
#

'emission' module?

stuck palm
late bobcat
night mural
#

i think right now your parcticles will play 1/10 of their lifetime and then disappear

late bobcat
#

idk if this could make sense

stuck palm
night mural
hexed terrace
night mural
late bobcat
#

oh, it's a component? i thought i was just checking/unchecking constraint position onto the gameobject. Didn't know it was a component itself

night mural
#

not related to physics/rigidbody constraints (which it's worth noting are on the rigidbody and not the gameobject)

late bobcat
#

@hexed terrace ye now player is not taking damage when i hit with laser, but he's not taking damage from collision with enemies either

night mural
late bobcat
night mural
hexed terrace
late bobcat
#

yeye

hexed terrace
#

How big are the colliders on the player and the laser?

hexed terrace
late bobcat
#

basically whole model

hexed terrace
#

don't make me guess, just state it specifically..

late bobcat
#

i can make a video if you want

hexed terrace
#

Just give me the name of the gameobject from the screenshot?

#

Why make the question/answer any harder than that?

late bobcat
#

i'm trying to understand what you're asking for, not my interest to make things harder

#

but the answer is "whole model". Like the walking animation is moving around the whole model

hexed terrace
#

what .. is .. the "whole model" .. game object ... called ..

late bobcat
#

gorillafinalissimo is the player gameobject. "Testa" is child of the player gameobject from which the laser comes out

hexed terrace
#

the rigidbody is on gorillafinalissimo?

late bobcat
#

ye

hexed terrace
#

Put this log in both PlayerHealthSystem and Laser1 OnTriggerStay methods.. do not put it inside any If statements.
Get only the laser to hit something, and see if both are logged

Debug.Log($"on trigger stay for {gameObject.name}");

late bobcat
#

both are tagged

hexed terrace
#

I haven't used 2D physics, in 3D two components won't get the physics events.. only 1 will

late bobcat
#

same goes for me, first time using physics 2dray tbh

#

i just used colliders in the past

#

i'm probably gonna move the deal damage to player into the enemies script

hexed terrace
#

Do what Prakkus said, create a new empty game object, call it "Player", move the gorillafinalissimo as a child, move the laser as a child (so they're siblings), then use the constraint thing to make the laser follow

late bobcat
#

ye i can also try that

#

ty anyway @hexed terrace

merry harness
#

how do i delete prefabs after a certain amount of time after i initiate them

#

so for example after a prefabs spawns it deletes itself after a couple seconds

faint sluice
cosmic quail
faint sluice
cosmic quail
night mural
merry harness
night mural
#

bud you should really go do some basic unity tutorials

faint sluice
cosmic quail
#

if you use object pooling then you gotta do the update method (or a coroutine) anyways but yeah for now destroy(object, x) works

merry harness
night mural
#

you are learning how to do basic things

merry harness
night mural
#

'i'm learning how to high jump by trying really hard'
'bru you do not even know how to stand up'

merry harness
night mural
#

the basics of how unity objects work

faint sluice
cosmic quail
eternal falconBOT
#

:teacher: Unity Learn ↗

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

cosmic quail
#

good source for learning unity

merry harness
steel smelt
#

@merry harness iirc unity had a pretty solid learn section -- going through the scripting basics in order was a good choice, at least 10 years ago

faint osprey
#

ok so i have a scene called dungeon and when reach the end of that scene i reload the same scene passing some variables to static variables in a gameManager so that they stay across scenes however there not staying and just keep resetting

merry harness
faint sluice
faint osprey
merry harness
#

now, how do i save the refrence of the innitiated object

cosmic quail
steel smelt
#

His variables are static

#

not the instance of the class

night mural
steel smelt
#

If you set a value and that value is not what you expect, right click the variable in your editor, look for references and find out where you are setting it again.

faint sluice
merry harness
cosmic quail
faint sluice
merry harness
#

the function i know is """" function logit() {console.log("Hello World")}; logit(); """"""""" output is Hello World

#

from Javascript

#

i dont think it has the same meaning here

#

so thats what im confused about

steel smelt
#

you need to follow tutorials 100%

#

the learn section

#

no amount of explaining via discord could cover the basics you do not currently understand

cosmic quail
#

@merry harness !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

viscid harbor
#

Hi all, I could use some help, trying to make a snake/tron clone for practise and I'm struggling to figure out how to make the snake body segments loop nicely with the head.

merry harness
# steel smelt you need to follow tutorials 100%

im watching a tutorial on youtube on unity, guy is currently making a flappy bird clone, i could skip ahead and figure out what code he wrote but then what am i learning if i dont struggle to get it and directly copy it down

viscid harbor
faint sluice
faint osprey
viscid harbor
#

How do I prevent the body segments from stuttering like that? Is there a simpler/better way to achieve this?

steel smelt
#

@merry harness No one is suggesting you do that. The learn section has tutorials on how to write code at the most basic level. Once you understand that, you have a better toolkit to create what you actually want to create.

faint sluice
#

Same case with "instantiate", hover over it and you will see what it returns (spoiler: it returns the object you just instantiated)

#

But again, highly recommend to atleast get basic feel of what the language is about before dipping toes in deep waters
!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

autumn tusk
#

would it be possible to change the prefab of a child while the game is running

faint sluice
autumn tusk
#

basically the idea im going for is a multiple weapon system for a topdown shooter

faint sluice
# autumn tusk whats the difference

When you're in playmode, the prefab in scene becomes copy and their own individual objects. I.e. they are unlinked from prefab and you can do whatever you want with them

Same way when you change the original prefab from asset while in playmode, the changes won't reflect in the hierarchy until next session

verbal dome
autumn tusk
#

pretty much

faint sluice
autumn tusk
#

just have different predefined weapons with their own statistics and when the player picks it up, having it swap between said weapon

#

so if my player is holding an mp5 and picks a sniper off the ground, it replaces the held mp5 with a sniper

faint osprey
#

im using dont destroy on load to keep my object from being deleted when i reload my scene however this means i have two of the objects now when the scene reloads

autumn tusk
faint sluice
faint sluice
night mural
# autumn tusk is there documentation for this

Think of the prefab as a 'template' that's used when building the game to help you divide things up into reusable pieces. At runtime, everything in the scene is just gameobjects with scripts on them and 'prefabs' as a concept no longer matter. In other words, the scene is all that matters and you are free to modify it at runtime however you need to for your game.

#

just because the player prefab has one kind of gun doesn't mean you can't swap that out as part of gameplay (and doing so won't affect the prefab itself)

verbal dome
lethal flax
#

Hey Guys, (i am 15) I wanna start to learn creating games. Do you guys maybe have some tips on how i can achieve to start? I tried sometimes to learn it online but didnt really work. Happy for any tips 🙂

eternal falconBOT
#

:teacher: Unity Learn ↗

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

brave robin
#

It means you never assigned anything to that reference variable before you tried accessing whatever it refers to.

Light someLight = null;
someLight.intensity = 2f;

This won't work, as someLight is null, so trying to access its intensity will give you a null reference exception.

summer stump
#

That is not really a solution, it just prevents the error

#

Yeah, as contrivance said

brave robin
#

If you're using [SerializeField], then it means you have the reference variable exposed in the inspector for your script, so make sure it's actually filled in with something in the inspector.

summer stump
#

The script reference (class) is what is null

#

Not the variable. Especially because bool cannot be null

brave robin
#

Then we'd need to see the code to understand this further, as a bool variable should not be causing a null reference exception

#

It must be the reference variable that refers to the class that contains the bool, that is null instead

#

Do you have rb, anim, and sr filled in for the inspector of each object that has this script?

#

oh wait, you getcomponent for them, so nm

#

Though those might still fail if the object doesn't have one of those components

summer stump
#

Either the audiosource or checkpointscript is null

#

I assume you're error is from one of those

#

Then checkpointscript

#

Where do you assign that?

#

You CAN drag and drop it

#

To the variable. Yes

brave robin
#

You can't refer to a variable on checkpoint in the same IF conditional as the one that checks if it's null
If conditionals check all of the conditions at once within the same block, so it's not stopping early if its null

languid spire
#

Note your else could NRE

if (checkpoint != null && checkpoint.CheckpointReached == true) // this is what doesnt work
        {
            anim.SetTrigger("checkpointDeath");
        }
        else if (checkpoint.CheckpointReached == false)
brave robin
#

When you select the object in the editor, on the right side: that's called the inspector.
You need to fill in all the fields you've exposed, otherwise they're just empty and null

cosmic quail
languid spire
#

CheckPoint is null

brave robin
#

That's better. It won't solve your underlying problem, but at least it won't NRE if checkpoint is null.

shell sorrel
#

really if its not valid or working if checkpoint is null, might as well let it nre and blow up in the devs face

brave robin
#

Do you have something elsewhere that is supposed to inject the checkpoint into this script?

languid spire
#

then you need a way to save the object across scenes DDOL is favourite

brave robin
#

I don't see a method in your script that would allow something else to change the Checkpoint variable

faint osprey
brave robin
#

So you've got this object with a PlayerLife component in Scene A, and in Scene B you've got checkpoints and other stuff.
I'm guessing you're loading scenes additively, so Scene A and Scene B coexist.
When Scene B is loaded, the PlayerLife component in Scene A needs to know about the checkpoint when it dies.
So far this is what you want?

vague dirge
#

Hello, I'm currently handling ground collision with a Physics.CheckBox and resetting the gravity velocity of my character (a RigidBody, with custom gravity physics), but it's starting to be really annoying and I'm constantly tweaking values because the model slowly sink into the ground... Would there be a more efficient way to deal with ground collisions ?

fierce shuttle
# faint osprey that worked however my script loses all of its in scene refrences

When you reload a scene (or load any scene in general), the previous scene is unloaded, along with all the references in that scene, and then the next scene is loaded (or in your case, the same scene is loaded again) - if your object had references in the scene before the reload, those would be lost when the scene got unloaded - if your object needs these references, you could maybe setup events to assign your references or try to decouple your object from the scene (depending on what this DDOL object is meant for, and what references it requires)

cosmic quail
fierce shuttle
# vague dirge Hello, I'm currently handling ground collision with a `Physics.CheckBox` and res...

Your character should not be "sinking" unless your applying gravity when it shouldnt (maybe your "grounded" check is not true when it should be), or you have "use gravity" checked on the rigidbody, typically I use a sphere cast a few units above the feet so the bottom of the sphere barely extends outside the bottom of my players capsule collider, I find it gives the most accuracy for most of what I need ground checks for, though providing your code may also help investigate what may be going on with your logic

faint osprey
#

and ive done that but its not refrencing

cosmic quail
vague dirge
#

And you think a checksphere is better than à checkbox btw ?

summer stump
#

Think about a class as a concept. You have INSTANCES of that class that are actual things in memory.
For example, say you have a class called Apple. It has a variable called color.

If you say what color is Apple, that makes no sense. Apples are all different colors.
If you say what color is THAT Apple, that is actually something that can be answered.

Right now, the compiler doesn't know which Checkpoint script you're talking about. It is irrelevant that there may be only one, because you COULD make more in the future, and the compiler won't assume.

You have to point at your CheckpointScript. Which is called referencing

https://unity.huh.how/references

fierce shuttle
# vague dirge And you think a checksphere is better than à checkbox btw ?

Depends on the kind of environments you have/plan to have, and the kind of edge cases your ground check needs to cover - for example, a cliff, or a stair case step, with a box, "grounded" could happen in a way your character might appear floating off the edge, if the corner or sides of the ground check comes in contact with the cliff, if you plan on having slopes it may be difficult to climb - with a sphere the corners are rounded so you can get much closer to those types of edge cases, but if everything if your game is all 90-degree angles with no slopes then either shape wont make much of a difference

cosmic quail
fierce shuttle
vague dirge
summer stump
#

You are not dumb, you are learning.
Did what I said make sense? Which part are you still struggling with?

Btw, in that site, Serialized References is talking about dragging objects into the inspector

fierce shuttle
# vague dirge No

If your ground check is true and your still sinking, then it sounds like your gravity code is either not getting reset for conditions where your ground check is true, or your still applying gravity in those conditions

vague dirge
fierce shuttle
eternal falconBOT
vague dirge
wind raptor
#

I have a simple, lightweight application that I will be using in-house only. Are there any major disadvantages to using a development build longterm, just so I have access to the console when needed?

fickle stump
#

!code

eternal falconBOT
spiral narwhal
#

Why can't my script access the private variable of an inner class? Does that generally not work in C#?

        private void DestroySelf()
        {
            foreach (var drop in _drops)
            {
                var amount = Random.Range(drop._minAmount, drop._maxAmount); // <--- issue
            }
            
        }

        [Serializable]
        private sealed class Drop
        {
            [SerializeField] private ItemSO _item;
            [SerializeField] [Range(0, 100)] private float _chance;
            [SerializeField] private int _minAmount;
            [SerializeField] private int _maxAmount;
        }
spiral narwhal
#

So in C# I can't access private members even if they're of inner classes?

rare basin
#

wdym inner classes

summer stump
#

Private is an access modifier meaning only that class can access it

hexed terrace
polar acorn
swift crag
polar acorn
swift crag
#

A nested type can access its parent's private members, though.

rare basin
#

i guess it's just a second class, but in the same file

#

not nested

swift crag
#
public class Outer { 
  private int x;
  
  public class Inner {
    public void DoThing(Outer outer) {
      outer.x = 123;
    }
  }
}
minor saddle
#

I'm pretty new to Unity, if I'm clicking a button is it just a case of switching the canvas or is it better to use scriptable objects?

cosmic quail
swift crag
#

scriptable objects have nothing to do with UI

eternal falconBOT
#

:teacher: Unity Learn ↗

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

minor saddle
rare basin
#

do you know what scriptable objects are?

spiral narwhal
#

Oh I didn't know. I come from Java and that's how it works there

public class Main
{
    public void test() {
        var test = new Test();
        System.out.println(test._test);
    }
    
    private class Test
    {
        private int _test;
    }
}
fierce shuttle
# wind raptor I have a simple, lightweight application that I will be using in-house only. Are...

What kind of disadvantages are you thinking could occur? If you are using Development Build as you work on versions of your game thats fine as you said you get access to the console and can inject your own UI for displaying those console messages in a build, maybe for a small group of testers it is fine as well, though for release you may want to disable that mode, and logging along with a release in general, as logging does impact performance, especially when logs happen every frame or very frequently

swift crag
#

but yeah, no special access for the containing type

minor saddle
spiral narwhal
#

Gotcha, good to know

rare basin
minor saddle
rare basin
#

they are not related

#

learn what ScriptableObjects are

wind raptor
# fierce shuttle What kind of disadvantages are you thinking could occur? If you are using Develo...

Are the performance hits of a dev build just related to the logging? I'm not too worried about that. I'm definitely not printing something every frame. A couple times a second at most.

I'm mostly trying to decide if it's worth trying to build my own faux "console" for the final build, or if it's fine just to use the default dev console. For my purposes, I'm going to want access to one or the other long term

swift crag
#

e.g. opening a "Settings" screen from the main menu

timid saffron
swift crag
#

You can activate a different canvas's game object, or you can just activate the game object that holds the settings menu UI

swift crag
#

I do the latter, but I probably shouldn't...

#

since that means that there's one enormous canvas

#

Note that different canvases will be completely separate from each other

minor saddle
swift crag
#

you won't be able to show two screens at once and have the automatic layout position them one after the other

#

Note that most of this page is probably not relevant to you right now

#

I just remembered reading the "multiple canvases" thing

spiral narwhal
#
Destroy(gameObject)
return true;

Would this still wait for the return type before destroying itself?

fierce shuttle
# wind raptor Are the performance hits of a dev build just related to the logging? I'm not too...

AFAIK, logging is the major performance hit of dev builds - for tooling, its up to you how you want to handle it and what you need, personally I think having your own console is nice cause you can setup more control over which logs you want to see and when you want to see them (for example, you could group logs sent from specific classes, or update a single log with new data), though tools in general, usually are not included in a release intended to be published/"shipped"

wind raptor
faint sluice
earnest atlas
#

Any guide on how to correctly implement unity input system?? I looked up a guide and person who uses it made it completly differently