#💻┃code-beginner

1 messages · Page 532 of 1

rancid tinsel
#

the only place I'm calling the coroutine from outside of the script is in a different script in start which is a singleton

summer stump
#

That is not how you do StopCoroutine

#

you need to cache the routine as a variable and pass that as the parameter

rancid tinsel
#

ah

summer stump
#

private routine myRoutine

myRoutine = StartCoroutine

StopCoroutine(myRoutine)

#

some psuedo-ish code

#

There is also StopAllCoroutines. Didn't look close enough to see if you have any others in that monobehaviour, but that is a choice too, and doesn't require caching anything

rancid tinsel
jade zenith
#

Should this be in a different channel?

summer stump
jade zenith
#

i also has a "starting visual studio" pop up but nothing changes after it finishes

#

i found this discussion thread but couldn't fix it

summer stump
#

Did you recently install visual studio? If so, have you restarted your computer since then?

rancid tinsel
#

am I crazy or this should work?

summer stump
#

I guess another important question is, have you EVER been able to open your script in vs?

summer stump
teal viper
rancid tinsel
jade zenith
#

This is my first time ever dealing with unity, so i should restart my pc?

summer stump
#

Make a public method that starts it

rancid tinsel
#

what's the IEnumerator overload for im confused

rancid tinsel
summer stump
#

In the class you have there:

public IEnumerator MoveCoroutine() { 
  //blah 
}
public void StartMove() {
  moveRoutine = StartCoroutine(MoveCoroutine());
}

In the other script

myReferenceToScriptA.StartMove();
#

Something like that

rancid tinsel
#

I've done that, but maybe I did it weird with my class set up

summer stump
rancid tinsel
#

it doesn't throw any errors but calling StopCoroutine(GameManager.Instance.moveCoroutine); in the SnakeController class doesn't stop the coroutine

summer stump
#

Ah yeah, you are starting it in SnakeController, so this won't work:
StopCoroutine(GameManager.Instance.moveCoroutine);

#

Store the routine in SnakeController, not GameManager

#

I mean.... I guess it could work, but why?
I recommend what I wrote above

rancid tinsel
#

oh wait yeah im an idiot i could literally assign it to SnakeController via the gamemanager

jade zenith
# summer stump yes

Restarted my pc and it's the same thing, would full shutdown and full reboot make a difference?

rancid tinsel
#

hmmm it still doesn't work for some reason

summer stump
rancid tinsel
teal viper
summer stump
#

because Move doesn't actually start the coroutine anywhere, just stops it

rancid tinsel
#

this is all I'm doing to it from the outside, aside from instantiating ofc

summer stump
#

Ok... I generally never start a coroutine in another class, so not sure if that would work

#

Can you try the indirect method I said above, just a single line public method that starts the coroutine, INSIDE of snakeController

jade zenith
summer stump
# jade zenith

Right click the solution and click reload with dependancies

teal viper
nocturne parcel
summer stump
#

Seconding the update route. If you want a delay, a float timer or a coroutine with a bool would probably be better, called in update and runs once

rancid tinsel
nocturne parcel
#

No judgement btw, just wanna know the reason

summer stump
teal viper
nocturne parcel
#

What they said.

rancid tinsel
#

but then id also need another bool to see if coroutine is playing no?

summer stump
#

Or at least as is. If it's a timer then no, you wouldn't need to check if it's running. Just the same bool toggling on and off

canMove = false
waitForSecondsRealtime
canMove = true
rancid tinsel
#

ah like that okay

teal viper
#

Or even better - enable/disable the controller script.

rancid tinsel
jade zenith
summer stump
#

Ah sick. Glad it worked!

teal viper
#

The rule of thumb in coding is "keep it as simple as possible". Using the enabled property of the MonoBehaviour would save you from defining an extra variable

rancid tinsel
nocturne parcel
#

Unless it's a bunch of stuff being enabled and disabled every frame, not really, no.

teal viper
steep rose
#

For your use case, you are most likely fine

nocturne parcel
#

Some people do over-optmize with this stuff. Like, I know some devs who don't even disable the UI, just reduce the alpha to 0 and make it not interactable.

rancid tinsel
#

also I got it to work with the canMove method!

teal viper
delicate lance
#

Do you guys have recommendations on following guides/ tutorials that uses best practices? I'm going through a game dev tv course and it uses 'FindFirstObjectByType' quite a bit and it doesn't sound like the best way to do things.

#

unless im wrong

rich adder
#

ofc there are better patterns like DI for example but its not really a big deal for game. No you dont want to use that function like update for exmaple

delicate lance
#

i get it though its a beginners course and thats bad practice

rich adder
#

they're calling FindFirstObjectByType in update?

delicate lance
rich adder
#

ohh okay. Update itself is nothing wrong

#

just be mindful what you do since that runs every frame

#

hence scanning every heriarchy object for a component is probably not the best every frame (and unecessary)

delicate lance
# rich adder ohh okay. Update itself is nothing wrong

Oh okayy thank you 👍 yeah i thought running it every frame would hit performance a lot but I'll learn profiler to see the results when its time to make a game. I want to make the jump to 'just develop' soon cause its been almost 2 weeks into unity and i really learn best by diving into the unknown - switching in UE and its a big difference but im loving it

#

well the UI is a big difference* haha

#

and C# keeps it all in one file where C++ needs a .cpp and .h file

rich adder
#

yes using unreal is like using a chainsaw to slice bread

rich adder
cloud moss
#

Hey y'all! There's something I'm trying to figure out here and I was hoping someone here would perhaps have a suggestion.

I have a function that I want to change scenes after certain conditions are met. It isn't just an "if" but more for it to wait until the conditions are met. However, the function is handling refs so I can't make it an IEnumerator, therefore it can't yield return a coroutine to load the scene. I was wondering if anyone had any ideas on how I could accomplish what I'm looking for?

north kiln
#

There is only one code language for unity

delicate lance
north kiln
#

!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

north kiln
#

There are beginner resources pinned to this channel if you're stuck getting started

summer stump
#

Create the script from Unity itself. It will be setup as needed with some boilerplate to get you started

The links I sent you in #💻┃unity-talk go over how to setup the code editor and create scripts

#

I do strongly recommend it over youtube

cloud moss
#

Unless I can make the function call a coroutine that itself calls a yield return coroutine?

summer stump
#

That one and then Junior Programmer at least

Essentials is just navigating Unity for the most part

delicate lance
#

game dev is a huge journey :3

#

thinking like a coder will be a journey itself but necessary

#

mine fried years ago so ill letchu know when i can relate 🤣

alpine fjord
#

Yeah, there is a lot to take in.

cloud moss
#

If I call the larger "WaitForTextBoxAndLoadScene" coroutine in a void function, will it wait to load the scene until "WaitForTextBox" is done?

#

in other words using an IEnumerator to store the other IEnumerator that needs to yield return

#

I was being hopeful, this did not work lmao

north kiln
cloud moss
#

Yes

#

Basically I need:
void function > if condition > (other code) > wait until [x] is met > load scene

#

and obviously those last two things don't really jive with the encapsulating function being a void

#

Some research says a helper coroutine may help so I'm trying that rq

#

Helper coroutine did it!

zinc pewter
#

is Assembly-CSharp.csproj only used by an IDE like Rider or Visual Studio and not Unity at all? (ie if im using say Vim or Emacs, then .csproj files aren't needed?)

naive pawn
#

more generally; if that file exists without opening an ide, then it's probably not specific to an ide

rain solar
#

can anyone help me find the math for shadow depth maps. Ive been looking for literal hours and i cant find the math anywhere

median rune
#

Hey guys quick questions is this normal when using unity ? My code is grayed out it says - "IDE0051: Private Number 'Unit Update ' is unused". Wonder if anyone else experienced this ?

naive pawn
#

it's a bug with the most recent version of vs afaik

median rune
teal viper
rain solar
teal viper
#

In simple words it should be something like rendering the objects from the shadow source perspective into a depth buffer.

rain solar
rain solar
teal viper
teal viper
rain solar
#

right but whats the math

#

its supposedly all linear algebra

teal viper
#

There isn't one specific math. It involves a lot of separate steps.

rain solar
#

which steps

teal viper
#

The ones i mentioned earlier

rain solar
#

what you said earlier could apply to literally anything under the umbrella of rendering

#

im talking specifically about a shadow map

teal viper
#

Shadow map is rendering though. It's just rendering the objects from a certain perspective.

rain solar
#

right, so whats the math to do that?

teal viper
#

Are you asking how to calculate the depth of a pixel in the shader?

rain solar
#

yes

teal viper
rain solar
#

i thought i did

teal viper
#

No. You were very vague. As I said, rendering the shadow map is a process with many steps. Calculating the pixel depth is just one small step in the whole process.

Anyways, the way I understand how it's done is you take a vertex position in clip/view space in the vertex shader, pass it to the pixel shader with interpolation. And that's basically it. The interpolated value is the depth of the pixel.

teal viper
#

It's a space inside the camera frustum usually having values from 0 to 1 iirc, where 0 corresponds to the camera near frustum plane and 1 to the far plane.

rain solar
teal viper
rain solar
teal viper
#

Of your mesh obviously. Whatever object it is you're rendering.

rain solar
#

is that somehow different than the global position of what im trying to render

teal viper
#

Of course. Meshes consist of many vertices - many positions that consist the object shape.

"Global position" - I assume you're referring to the object position is just a pivot point of the mesh.

rain solar
#

what if my mesh is a single vertex

teal viper
#

That's not possible. There would be nothing to render.

rain solar
#

my mesh exists theoreically, there is no actual mesh its simulated

teal viper
#

I think you can't have meshes with less than 3 verts physically.

rain solar
#

my mesh exists as a single coordinate

teal viper
#

Then it's not a mesh. Just a point in space.

rain solar
#

ok well how do i determine the shading depth of that single point in space

teal viper
#

The same way. Multiply the position by the view matrix.

rain solar
#

what is the view matrix

teal viper
#

You'll need to do a little bit of learning yourself. Google it.

rain solar
#

i have googled it

#

it says to multiply by the view matrix but not what the view matrix is

#

or at least the sources dont agree on what it is

teal viper
#

Then read from several sources and try to put that info together

rain solar
#

ive been reading for literally over 6 hours

#

this is my last resort before i just give up and go back to api programming

teal viper
#

Is there a specific thing you don't understand about it?

rain solar
#

every single source mentions exactly what a shadow depth map is but not one says how anything is calculated

#

i understand its a series of linear algebra ops but idk which ones

teal viper
#

It's not. It's a lot of simple math and other not math related steps.

rain solar
#

ok given a position in 3d space, i multiply it by the view matrix

#

what is the view matrix

teal viper
#

Its a matrix. A bunch of numbers. I don't know how it's calculated. You usually don't need to know it, unless you develop your own engine.

teal viper
#

To put it simply, a view matrix is one that when a position is multiplied by it, returns a vector corresponding to that position in view space.

rain solar
#

[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]
see now why couldnt they have just said a 4x4 diagonal

teal viper
#

Because it's not

#

It's a matrix. The have certain rules that apply to them. It's a math concept.

rain solar
#

ok but i need the numbers

teal viper
rain solar
#

this is beginner code

#

i am beginner

teal viper
#

So? How does it contradict what I said?

#

You might be a beginner, but this topic is not.

#

And while we're at that, just a recommendation, but start with something simpler if you're a beginner.

rain solar
#

ill move it though

teal viper
#

It's like you're trying to construct a nuclear reactor in your background without any knowledge in physics.

rain solar
#

im trying to gain the knowledge

#

i just cant find it anywhere

#

it feels like a secret recipe that is passed down but never written

teal viper
#

Start simpler, get there eventually. There is a lot of prerequisite knowledge to what you're asking and you seem to lack it.

median rune
#

Quick question for my problem is there a work around with this bug ?

ivory bobcat
ivory bobcat
median rune
#

ok I got that but , what would you mean your class doesn't derive from Unity Mono Behaviour component class.

ivory bobcat
median rune
alpine fjord
#

Or so I'm told.

median rune
ivory bobcat
median rune
#

Ill guess just leave at that and just wait until it gets fixed

#

thanks for the help @ivory bobcat and @alpine fjord .

alpine fjord
austere orbit
#

Heyo! I've got a doorway that my player can walk through on either side, and I'd like to enable post processing when the player walks through one side of the door (a box collider), and disable it when it walks through the other. I've attempted this script below, however it only resutls in post processing being enabled on either side of the door that the player walks through and I cannot for the life of me figure out why. I think I may be misunderstanding how Dot Products are calculated, does anyone know what the issue is? 😅

using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.PostProcessing;

public class DoorTrigger : MonoBehaviour
{
    public Transform doorCenter; 
    public PostProcessVolume postProcessVolume; 

    private void Start()
    {
        DisablePostProcessing();
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            Vector3 toPlayer = other.transform.position - doorCenter.position;

            if (Vector3.Dot((other.transform.position - doorCenter.position).normalized, doorCenter.forward) > 0)
            {
                EnablePostProcessing();
            }
            else
            {
                DisablePostProcessing();
            }
        }
    }

    private void EnablePostProcessing()
    {
        if (postProcessVolume != null)
        {
            postProcessVolume.weight = 1; 
            Debug.Log("Post-Processing Enabled");
        }
    }

    private void DisablePostProcessing()
    {
        if (postProcessVolume != null)
        {
            postProcessVolume.weight = 0; 
            Debug.Log("Post-Processing Disabled");
        }
    }
}
heavy knoll
#

Anyone know how to fix this problem i have with my jump?
I have my ground drag set to 10 so my player movement feels a bit less slippery
but when i jump my character barely goes anywhere in the air
i have a double jump too, so if i increase the force of the jump it might help the first jump, but the second jump would be way higher than it should be
with my ground drag being set to 10, i also move faster when i jump in the air which kinda feels odd
i cant really figure out how to get the right balance of having a non sliding character without manipulating the drag which in turn seems to mess everything else up

austere orbit
heavy knoll
austere orbit
heavy knoll
#

i tried messing around with physics materials and everything too, but couldn't really find a perfect working fix for it

austere orbit
#

(I personallydon't like using drag to recude slippery-ness, for the described issues, but I'm still a beginner :P)

#

You could try making the rigidbody kinematic while there's no input?

austere orbit
#

When I use GetAxisRaw it usually stops sliding as much :/

ivory bobcat
heavy knoll
#

and no friction material on player?

#

because when i have no friction material on my player and the drag is the default 1, even with Input.GetAxisRaw my player slides when i let go of my input

austere orbit
heavy knoll
austere orbit
#

Nope

heavy knoll
#

if i have no physics material and my drag set to 0, my player feels slippery

#

like i slide for about a half a second to a second after letting go of my input

austere orbit
#

Yeah I don't think that should be happening with GetAxisRaw, might be something else influencing it

heavy knoll
#

!code

eternal falconBOT
heavy knoll
austere orbit
#

Your public "groundDrag" variable is set to 0?

#

Oh you have some lerping for your move speed when you're dashing. That could be it

north kiln
heavy knoll
heavy knoll
austere orbit
ivory bobcat
ivory bobcat
#

Ah.. maybe I should cancel the update.. 😳

#

The latest verified was 5 days ago.

NOT fixed in 17.12.1
I'll verify if it persists in 17.12.2.

#

Alright, it's a no go.

median rune
lilac crow
#

Hello and good day everyone!🌹❤️
I have a little question.
In my game in have some datas that need to be sorted and used across multiple scenes. Like total scores, collected items and so on.
Is it better to save the records on a jason file based on a single scene save and load system or make a small local database for it? 🤔
Thank you for your time and guidance 🙏🏻

fickle plume
#

Whatever works for you. Usually using database is an overkill.

queen adder
burnt vapor
#

Most games use a custom binary format where they know the order of bytes. It is impossible to modify unless you know what format you use. Alternatively use an encryptor for your JSON data.

burnt vapor
#

Probably better if more context is given since it's unclear

queen adder
burnt vapor
#

I get that, hence why its "probably better if more context is given"

#

So @lilac crow is this for persisting data so you keep your score when you start up the game at a later point?

lilac crow
#

I want to use this datas like total score for unlucking new abilities and other things, it is kinda a currency, some of them will be modified.

#

And I don't want to be restored to non when I reload the gaim or start it again.
That's why I want to store them.

burnt vapor
#

Yes, then use files

#

Databases should not be used because you end up providing your game on user PCs where it is not a good idea to do this

#

If you were to provide a service which communicates data through an API or socket, then the serverside could very well use a database though

#

But locally you should just use files. Alternatively you could use SQLite since it provides the database as a file, but this has its own issues with encryption and such.

lilac crow
#

So JASON it is.
Here I come babe!!
.
.
Thank you all very much for your time and attention! 🙏🏻🌹❤️😘

chrome fern
#

guys any one of u uses the new input sys of unity

fickle plume
static cedar
#

Difference between ExecuteAlways and ExecuteInEditMode?

fossil drum
burnt vapor
#

Pretty sure ExecuteInEditMode is being deprecated in favour of ExecuteAlways

#

Docs only have one difference

To keep prefab editing mode open while in Play mode, use the ExecuteAlways attribute instead. If you do this, you must take care to ensure your runtime MonoBehaviour code does not modify the prefab you're editing in ways intended to occur only during gameplay. For more details, refer to ExecuteAlways.

quick pollen
#

oh you're using VS my bad

static cedar
#

So apparently, if you're having "Waiting for Unity to finished code execution." right at the start that runs essentially forever, it probably means there's an infinitely running code in an editor code somewhere.

static cedar
#

I'm using a recursive function in my case, i would have liked if it eventually threw a stack overflow exception. Would have been easier to spot.

cosmic dagger
#

yikes, that sounds scary . . .

naive pawn
#

tail call optimization, where tail calls are flattened into a single stack frame, so it wouldn't trigger a stack overflow

#

seems like c#/mono don't support this, but maybe the architecture does..? this is kinda low-level stuff i'm not super well-versed in

sage mirage
#

Hey, guys! I have a warning here. Why this is happening?

rich adder
burnt vapor
#

This is why recursion is something to be careful with

#

In this case you could perhaps use something like polly so it short circuits if you want to be 100% sure

vestal adder
#

hi how do i check if a button is pressed at the same time as one of the times stated in a list

vestal adder
#

on a keyboard

frail hawk
#

you need to be more precisely. you are aksing for ready code.

vestal adder
#

i have a bunch of times in a list and wanna check if a button is pressed at the same time as one of them

languid spire
#

so how is the list declared

vestal adder
#

what does that mean

frail hawk
#

what is the type of your list

vestal adder
#

float

cosmic dagger
vestal adder
#

List.Add(Time.time);

languid spire
#

it means what line of code defines your list

vestal adder
#

how do i compare anything to all the values in a list

cosmic dagger
#

the same way you compare two values against each other . . .

languid spire
#

for loop

frail hawk
#

List in c# are very powerful you can do many things. Find,Select use linq etc

languid spire
#

even .Contains

vestal adder
languid spire
#

no it wont, never test floats for equality

vestal adder
#

how come

languid spire
#

because 0.000001 != 0.000000

vestal adder
#

i will be doing it within a range its okay

naive pawn
#

but .Contains wouldn't

languid spire
#

then you still cannot use .Contains

real thunder
#

I wonder btw speaking of floats
if you type 1 or 0 as float
are they really 1 and 0?

naive pawn
#

yes

naive pawn
#

it's stuff like 16777217 and 0.6 that don't exist

cosmic dagger
naive pawn
naive pawn
naive pawn
cosmic dagger
#

though, that's not a float . . .

naive pawn
#

wdym by that

cosmic dagger
#

too many decimal digits (precision) . . .

naive pawn
#

it's a valid literal

#

it just isn't represented accurately

vestal adder
frail hawk
#

you need to round your float

vestal adder
#

i do know for loops but im not sure what i am supposed to do with it

rich adder
#

you compare results each iteration

cosmic dagger
# vestal adder what should i do then

loop through your list of times, get the difference between the current time and each iteration (element at the current index), then compare (that difference) to a threshold . . .

vestal adder
#

okay i get that thanks

real thunder
#

I got a GameObject with a layer which collides with nothing and have a dynamic rigidbody
And it got a bunch of other child GameObjects with different Layer Overrides (they don't have rigidbodis)
Somehow, one of the childs collides with the object it should be unable to
What's going on

burnt vapor
#

Judging from the context you gave? We don't know

naive pawn
real thunder
#

The idea behind it was to make it so all child colliders only collide with stuff they are supposed to and send callbacks on the main rigidbody

naive pawn
burnt vapor
#

Also, this is hardly a code question

real thunder
#

yeah... eh.. sorry

vestal adder
burnt vapor
naive pawn
# vestal adder i dont know epsilions

epsilon in math is an infinitesimally small number; in computing, we use it to define a threshold for saying 2 floats are equal
suppose we define an epsilon of 0.01, that means we want to define 0.99 and 1.01 as "close enough" to be equal to 1.00
and we can check that by doing abs(a, b) <= epsilon, to check that a and b are not more than epsilon apart from each other

naive pawn
#

(that epsilon is the infinitesimal float though, you don't want that for this usecase)

cosmic dagger
#

typically, i use my own threshold so i can control the range or precision of error . . .

vestal adder
#

i totally get that now

#

although i am encountering issues comparing lists to floats

naive pawn
#

you should not compare lists to floats

rich adder
#

you iterate through it

naive pawn
#

you should compare each float inside the list, to another float

#

that's what people were talking about with looping

#

"each" = loop

vestal adder
#

how do i extract each value from the list

naive pawn
#

loop

rich adder
#

the list is literally a bunch of elements, thats what loops are for

#

iterate through each one

naive pawn
#

foreach to get them directly, or for to get the indices too

vestal adder
#

like that

#

for (int i = 0; i < List; i++)

naive pawn
#

what would it mean for a number to be less than a list?

vestal adder
#

nothing

naive pawn
#

right, so i < List doesn't make sense

rich adder
#

You want the maxmium of the list

vestal adder
#

i thought there may be something im not understanding ab it

naive pawn
#

have you seen loops before?

vestal adder
#

yes

rich adder
#

or at least how many elements you got.

#

you need the .Count of the elements in list

naive pawn
#

iterating through structures is pretty fundamental; you'll need it more in the future, so best get comfortable with it now

vestal adder
#

i guess i have managed to avoid them so far lol

#

yeah ill go learn

rich adder
# vestal adder yes

an example. first one is on the house 🥄

        int[] numbers = { 10, 25, 7, 69, 50, 12 };
        int largest = numbers[0];
        for (int i = 1; i < numbers.Length; i++){
            var currentNumber = numbers[i];
            if (currentNumber > largest){
                largest = currentNumber; // update largest if current number is greater
            }
        }```
cosmic dagger
nimble mortar
#

Why would Rider automatically convert:

InventorySlotUpdatedSignal.Emit(
  inventoryIndex: useIndex,
  updateType: InventorySlotUpdateType.ADD,
  oldItemContainer: null,
  newItemContainer: newItemContainer
);

to

InventorySlotUpdatedSignal.Emit(
  inventoryIndex: useIndex,
  updateType: InventorySlotUpdateType.ADD,
  null,
  newItemContainer: newItemContainer
);

?

wintry quarry
#

That's weird!

#

What does the inspection say?

cosmic dagger
#

what happened when you tried it?

nimble mortar
#

Is seems like there are syntax style arguments rules but it seem like I have to choose either positional or named, I wish I could just tell it to not change it

atomic holly
#

Hello
I don't understand why I get an error when I do this :

using UnityEngine;

public class SetPlayerSpawn : MonoBehaviour
{
    private void Awake()
    {
        Debug.Log("Player spawn set to: " + transform.position);
        SingletonManager.instance.playerSpawn = transform.position;
    }
}
using UnityEngine;

public class SingletonManager : Singleton<SingletonManager>
{
    public Vector3 playerSpawn;
}

Unity send me this error : ```
NullReferenceException: Object reference not set to an instance of an object.
SetPlayerSpawn.Awake () (at Assets/Code/Scripts/Player/SetPlayerSpawn.cs:8)

cosmic dagger
atomic holly
cosmic dagger
#

then instance is probably null . . .

limpid tangle
#

Why does this error appear? I’ve done everything possible and nothing works. I wanted to try with a tag, but you can't use more than one.

cosmic dagger
# atomic holly yes

double check that it's assigned before attempting to access it from the SingletonManager class . . .

languid spire
#

the error is not even in the script you posted

atomic holly
cosmic dagger
#

seems you tried everything on the wrong . . . thing . . .

runic lance
#

seems to be this line actually
if (handScript.mainHand == null)
most likely you don't have a valid reference for the handScript

cosmic dagger
limpid tangle
limpid tangle
naive pawn
#

right because you're still trying to dereference handScript

cosmic dagger
ivory bobcat
limpid tangle
ivory bobcat
cosmic dagger
cosmic dagger
#

you need to log if the value is null for all reference variables to determine if they are actually assigned . . .

#

something is not assigned when you think it is . . .

#

before the error line, log the value of the variable . . .

ivory bobcat
#
    private void Update()
    {
        if (handScript == null)
        {
            Debug.Log($"We don't have a hand script attached to this component - click me once", this);
        }
        else if (handScript.mainHand == null)
        {
            print("a");
        }
    }```Check if it's null before using it.
#

Click on the log and see which object highlights in the scene-hierarchy.

limpid tangle
#

let me check that

limpid tangle
ivory bobcat
final sluice
#

What do i use to detect a button continuously be held down and what do i use to detect a button which was just pressed once ?

wintry quarry
final sluice
#

The legacy system

wintry quarry
#

GetButtonDown for initial press vs GetButton for holding

limpid tangle
limpid tangle
cosmic dagger
limpid tangle
#

Sorry for wasting your time with a silly mistake

cosmic dagger
#

from the very beginning we told you it was the handScript . . .

#

always check and don't assume . . .

limpid tangle
cosmic dagger
#

hey, it's figured out. that's a win!

bright hull
#

Hello guys, I'll get to the point. I'm really a newbie but I wanna learn unity and C#. I know most of you are professional and I need help. I'm waiting suggestions.

#

(I'm trying to make some projects)

ivory bobcat
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

ivory bobcat
#

Learn and skip-around/do-things at your own pace.

bright hull
#

Looks like good.

#

Thank you.

ivory bobcat
#

An example of skipping to the programming essentials chapter.
Do note that there's more to gamedev than just programming though.

median rune
ripe dagger
lofty sequoia
#

I have a button on a canvas that keeps changing it's position only after a windows build and only when I anchor it to the bottom left. When I anchor it to the top left, it stays in it's rect transform position of x:50, y:50.
But when I anchor on the bottom left (no change other than changing the parent's anchored position) it keeps changing it's position to Rect Position: X:-50, Y:-50 which is off screen.

coarse wasp
#

Hey all I'm encountering an issue when trying to create a shader in URP, anyone have suggestions how to fix this issue? I can't seem to find anything online. Shader error in 'Custom/OceanShader': unsupported shader api at Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl(238) (on d3d9)

torpid igloo
#

i have an array of an enum that needs to be displayed as a SerializeField in the Unity editor(see image for example), and i need to sort it(the array) to be in the order of declaration in the enum(see image). how can i implement this?

cosmic dagger
ripe dagger
# cosmic dagger i would start with a flappy bird, angry bird, and a 2d mario clone. you'll find ...

alright, but im trying to make something like Blek

https://youtu.be/JXv8eRkHlb4?si=2llujOCjDdyPvEDt

would you try something else, now that you know the target is something like blek?

Gameplay Video of "Blek" by AppTrendr.

iTunes Link: [https://itunes.apple.com/us/app/blek/id742625884?mt=8]
Subscribe [https://www.youtube.com/user/AppTrendr/videos?sub_confirmation=1] AppTrendr

The latest iOS and Android Gameplay, Trends, Review, Preview, Trailer, Cheat Code, Walkthroughs & More.

iTunes Description:

• Featured by Apple: B...

▶ Play video
naive pawn
torpid igloo
#

no

naive pawn
#

why not just have a list of bools for each enum member then

torpid igloo
#

it shouldn't have more than on instance of each enum member

cosmic dagger
naive pawn
#

you don't need the flexibility of a list, so don't use a list, use a more constrained structure

#

that way the validation is built into the structure

fallen owl
#

Hi everyone, kind of a beginner coder here and I was wondering why is the y value of my Cinemachine offset not changing with this code? What am I doing wrong?

EDIT: I'm trying to smoothly change my _currentYAngle from 4 (the initial value) to 10 when they enter a triggerbox and then back from their _currentYAngle to 4 when they exit.

Here is the script

eternal falconBOT
fallen owl
wintry quarry
#

You're only modifying your own variable, which isn't used anywhere

#

_currentYAngle

fallen owl
#

Ooooohhh, now I understand!! Thank you very much! 😄

modest linden
#

I need help with a script :using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ProjectileDeleteScript : MonoBehaviour
{
public float Lifespan;
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    this.Lifespan -= Time.deltaTime; // Decrease the lifespan variable
    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Zombie")
        {
            Destroy(base.gameObject, 0f);
        }
    }
    if (this.Lifespan < 0f) //When the lifespan timer ends, destroy the BSODA
    {
        UnityEngine.Object.Destroy(base.gameObject, 0f);
    }
}

}

#

this is on a prefab, and the ontriggerenter is not working

eternal falconBOT
modest linden
#

ok

naive pawn
modest linden
#

It still is not working, how do i do a debug.log?

cosmic dagger
modest linden
cosmic dagger
modest linden
#

ok

modest linden
naive pawn
#

you need "2d" in the method name for that

cosmic dagger
cosmic dagger
#

let's give it a try and see what happens . . .

modest linden
modest linden
naive pawn
#

is your method declaration correct now

modest linden
cosmic dagger
#

then continue to the next link if you are not receivng a trigger message . . .

#

at the bottom of that page is another link if you still do not receive a message . . .

modest linden
#

the site shows this

cosmic dagger
#

is your collider set to trigger?

modest linden
cosmic dagger
#

if the objects are on the same layer, they will collide with each other. it would only be a problem if you manually change one of the objects' layers. by default, they're set to the same layer . . .

cosmic dagger
modest linden
#

i added a box colider 2d to the prefab!

cosmic dagger
#

you can't collide with anything without a collider . . .

naive pawn
modest linden
cosmic dagger
# modest linden Im confused?

physics layers are only an issue if you manually set layers for your GameObjects. if you did not, then it's not the problem. by default, all GameObjects are assigned to the same layer, so this is never an issue . . .

sharp abyss
naive pawn
#

are they perhaps colliding with each other

sharp abyss
#

I solved it but dont know what I did.Changed the script a bit.Deleted complex things.

uneven plover
#

Hello, I have a text child of my button is there a way to rotate the button without rotating the text ?

button.image.transform.rotation

ive tried to rotate directly the image of the button but it doesnt work

lofty sequoia
#

When I call Button.GetComponent<RectTransform>().anchoredPosition = new Vector2(100f, -100f);
in the Start() nothing happens.
If I add a coroutine that calls the EXACT SAME THING -- Button.GetComponent<RectTransform>().anchoredPosition = new Vector2(100f, -100f);
but a second later, it works...

night mural
blissful lagoon
#

how can i not see velocity in my debug panel for rigidbodies??

#

i remeber doing this before?

slender nymph
#

it's not there in the latest versions

blissful lagoon
#

wat

slender nymph
#

you can display the velocity by assigning it to a serialized field on some other component, or print it to the console

blissful lagoon
#

omfg wtf

#

whhy?

slender nymph
#

the rigidbody component's inspector is incredibly slow because of all the stuff it does to display things. simply viewing other objects can be an improvement in performance because of how fuckin slow it is

blissful lagoon
#

ah i see

#

does this effect runtime performace? i feel like i dont care if it doesnt

slender nymph
#

only runtime in the editor while viewing the component in the inspector

blissful lagoon
#

thats so stupid

#

but if im on the debug panel chances are i dont care about performance???

#

like idk wtf

slender nymph
#

typically people still care about the performance of their game while viewing debug info. just because you don't, doesn't meant that nobody else does. i gave you alternatives to view the velocity, pick one and stop complaining.

west radish
#

Oh yeah, it's amazing how much performance would take a beating if you got the inspector updating everything all at once

wintry quarry
#

Pretty sure you can see it in there

#

Yeah you can track Rigidbody and Articulation body velocities there

orchid mauve
#

I cant seem to get my slider to connect to my mixer audio to allow the player to adjust the audio in unity

#

this is the code that I have currently

#

with a serialized field for the mixer

cold elbow
#
    {
        
        bounceStenght += 1/100;

        switch (collision.gameObject.layer)
        {
             case 6:
             case 7:
                logic.gameOver();
                birdIsAlive = false;
                myRigidbody.linearVelocity = Vector2.up * (1/bounceStenght);
             break;
      }
    }
}
#

I'm getting this error

slender nymph
#

bounceStenght is likely 0

cold elbow
#
UnityEngine.Rigidbody2D:set_linearVelocity (UnityEngine.Vector2)
BirdScrip:OnCollisionEnter2D (UnityEngine.Collision2D) (at Assets/BirdScrip.cs:34)```
#

yes

slender nymph
#

1/100 is also 0 because it is integer division

cold elbow
#

but I'm incrementing it

cold elbow
slender nymph
#

and yet 1 and 100 are both ints therefore 1/100 is 0

#

you need at least one float literal in your division for the result to be a float. so 1f/100, 1f/100f, or 1/100f would all work

cold elbow
#

idk why but when I assign 0.01 to a float variable it gives me compilation error I don't think this happened to me in other programming languages

slender nymph
#

0.01 is a double not a float. there are beginner c# courses pinned in this channel if you don't know the basics

cold elbow
#

fair enough

hollow obsidian
#

Hey today I get the challange in jr Programmer with persistence. Creating savefile and stuff like that. Is there a better tutorial or smht? I do the challange make all finish but dont understand how this System works. 3h and brain hurts only to save a best score und username from input field.patouses

teal viper
austere orbit
hollow obsidian
teal viper
hollow obsidian
#

Like static Instance stuff. Hard to explain. And See many games using dot save files or something. And on the course it's json files but json files are easy to manipulate outside the game?

hollow obsidian
teal viper
hollow obsidian
#

Idk but later Missions on the pathway feels like unity Was lazy to explain that with more Samples or something... Idk before every chapter 3-8h and the save file stuff only a 30 min chapter. notlikethis

nocturne parcel
teal viper
hollow obsidian
#

It was that. But have not the Code now because im in bath. 😅

hollow obsidian
teal viper
#
  1. Don't rely on chat gpt(or any other llm/ai). At least not as a beginner.
  2. Read through manuals and documentation of API that you don't understand or see for the first time.
  3. Make sure you have the basics right. That implies learning the syntax and the different C# keywords, like static
teal viper
#

Donno. Complaining?

hollow obsidian
#

I searched since hours for a better tutorial to understand it. I mean lazy guys skipped that maybe idkreally

teal viper
#

What exactly were you searching for?

alpine fjord
#

Don't rely on chatgpt because it is wrong just as often as it is right.

teal viper
#

"searching for better tutorial" already smells like laziness to me

hollow obsidian
nocturne parcel
#

You mean how the data is saved?

hollow obsidian
hollow obsidian
teal viper
nocturne parcel
#

Code-wise or internal works of the language?

hollow obsidian
#

It's cool the tutorial say Do this and this and you get this. But how the background System works idk

nocturne parcel
#

Search for serialization in C#. Not tied to Unity.

hollow obsidian
nocturne parcel
#

Basically, you want to understand how to transform an object into something that can persist between states. It goes beyond just saving a game.

teal viper
teal viper
hollow obsidian
teal viper
#

That's another habit you're gonna get used to. Once you start getting into more advanced topics, there's gonna be not manual or explanation. Only code of other people that implemented it and documentation.

nocturne parcel
#

You talked about JSON and how it can be "easily manipulated", but that's the wrong way to see things. You need to understand when JSON is used.

teal viper
#

All I see is complaints on how hard it is and stuff like that.

nocturne parcel
#

And it is in fact because you want to easily manipulate the data

hollow obsidian
nocturne parcel
#

Many tutorials use json because it makes it easier for you to see what's being saved

teal viper
#

Break it down into small questions. Things you have difficulty understanding. And ask them in order. Don't just throw a "I don't know how the system works".

nocturne parcel
#

But either way, doesn't matter the format you use, data will be manipulated and poked at by the end user

#

Binary, json, xml

quartz sail
#

hi can someone help me understand my code wont shoot out the bullet for my Ai?

hollow obsidian
#

Yeah i looked inside the json try to understand which date He save how and from where

quartz sail
nocturne parcel
#

It's the wrong approach in how you are trying to understand. You basically asked "why json bad" instead of "why use json"

nocturne parcel
#

Implying that the tutorial is wrong for using json, when json has many use cases

quartz sail
rocky canyon
#

prettyprint

nocturne parcel
#

So, you didn't search about json

hollow obsidian
rocky canyon
#

json is a big ole' string

teal viper
eternal falconBOT
quartz sail
#
using System.Collections.Generic;
using UnityEngine;

public class AiShooter : MonoBehaviour
{

    public GameObject Bullet;

    //shot timings

    private float timerShots;
    public float timeBtwShots = 0.25f;

    public float fireRadius = 25f;
    public float Force = 2000f;



    // Update is called once per frame
    void Update()
    {
        float distance = Vector3.Distance(PlayerMove.playerPos, transform.position);

        if (distance <= fireRadius)
        {
            AI_FireBullet();
        }
    }

    void AI_FireBullet()
    {
        RaycastHit hitPlayer;
        Ray playerPos = new Ray(transform.position, transform.forward);

        if (Physics.SphereCast(playerPos, 0.25f, out hitPlayer, fireRadius))
        {

            Debug.Log("shooting");
            if (timerShots <= 0 && hitPlayer.transform.tag == "Player")
            {
                GameObject BulletHolder;
                BulletHolder = Instantiate(Bullet, transform.position, transform.rotation) as GameObject;

                BulletHolder.transform.Rotate(Vector3.left * 90); //sometimes needed sometimes not

                Rigidbody Temp_RigidBody;
                Temp_RigidBody = BulletHolder.GetComponent<Rigidbody>();  

                Temp_RigidBody.AddForce(transform.forward * Force);

                Destroy(BulletHolder, 2f); 

                timerShots = timeBtwShots;
            }
            else
            {
                timerShots -= Time.deltaTime;
            }
        }
    }
}

(debug is working as well so it tech is "shooting")

nocturne parcel
#

And I'm telling you that you didn't search about jsons and its use cases and what it essentially does.

#

And why other games may use different formats

#

Which is not much of a you problem tbh

slender nymph
quartz sail
slender nymph
#

there are beginner c# courses pinned in this channel if you don't know how to use the variables you already have . . .

nocturne parcel
#

I think it comes down with the fact that people who are starting with game dev don't really understand what data is, as they don't usually have a computer science background.

#

So there is not much understanding with what to do with data

#

And that's why you should always start with a general coding course

#

Instead of beginner game development ones

quartz sail
slender nymph
#

no, it just means the spherecast hit something

quartz sail
#

but its only meant to hit the object tagged with Player and only shows when that happens?

nocturne parcel
#

The debug is outside the if checking the player

quartz sail
#

im sorry if im not understanding properly

slender nymph
quartz sail
nocturne parcel
slender nymph
nocturne parcel
#

You either move the log to the second if, or, as boxfriend suggested, print more useful information.

#

Either way, I believe the problem is that AddForce is so fast it ain't registering the collision.

#

Or, like, you are not even noticing it

#

2000f force is crazy

quartz sail
slender nymph
#

great! so what exactly did it print?

quartz sail
nocturne parcel
#

I see

slender nymph
slender nymph
# quartz sail

now print the tag of what was hit and make sure that is what you expect since you are using the tag for the condition

quartz sail
nocturne parcel
#

I mean, how are you using the same amount of force for a bullet and the player?

#

Like, the problem is the quantity

quartz sail
#

thanks figured out the issue

slender nymph
nocturne parcel
#

Trry putting force at 30f and see what happens

#

Oh ok, what was it?

quartz sail
#

i forgot to actually tag my player...

nocturne parcel
#

lol

#

happens to the best of us

slender nymph
nocturne parcel
#

Now I'm curious how the addforce 2k is working because that's, like, a lot

quartz sail
# slender nymph you shouldn't be using deltaTime with your forces, you shouldn't be applying for...
using System.Collections.Generic;
using UnityEngine;

public class FireObject : MonoBehaviour
{

    public GameObject Bullet;

    public float Force = 2000f;


    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            GameObject BulletHolder;
            BulletHolder = Instantiate(Bullet, transform.position, transform.rotation) as GameObject;

            BulletHolder.transform.Rotate(Vector3.left * 90); //depends on rotation of weaponholder

            Rigidbody Temporay_RigidBody;
            Temporay_RigidBody = BulletHolder.GetComponent<Rigidbody>();

            Temporay_RigidBody.AddForce(transform.forward * Force);

            Destroy(BulletHolder, 1f ); 
            
        }
    }


  

    
}

this is my character shooting but when i dont get the 2000 force it shoot but wont rlly go forward even now it doesnt go forward as much

slender nymph
slender nymph
nocturne parcel
#

Yeah, it's because you should be using FixedUpdate

slender nymph
#

that's not why . . .

nocturne parcel
nocturne parcel
quartz sail
slender nymph
slender nymph
#

i feel like i'm taking crazy pills today with all this repeating myself i have to do

nocturne parcel
#

Still, use FixedUpdate

#

For the cast at least

slender nymph
#

there is nothing wrong with it being in update

nocturne parcel
#

Hmm I dunno, when doing casts it can get really innacurate

quartz sail
nocturne parcel
#

Unless you are changing the position directly

slender nymph
slender nymph
nocturne parcel
#

Are you sure?

#

I do use it sometimes when, like, doing a kinematic controller

#

But I usually use Translate

slender nymph
#

yes, the state of physics is updated on FixedUpdate frames. there are no extra physics updates between those that would cause any sort of "inaccuracy", it just might be visually inaccurate because one might assume that a raycast should hit when they are looking at an interpolated object

nocturne parcel
#

I was under a misconception then

quartz sail
#

so i change this
Temporay_RigidBody.AddForce(transform.forward * Force);

into this?
Temporay_RigidBody(0, 0, thrust, ForceMode.Impulse);

nocturne parcel
#

ty for sorting that out

slender nymph
slender nymph
#

just make sure to reduce the amount of force by a lot

quartz sail
#

i appreciate the support! thanks

nocturne parcel
#

But the wrong force mode in the update still can cause problems, right? Like the default is applied in each fixedupdate frame

slender nymph
#

right, the only acceptable forcemodes to use in Update are the ones that add a one-off force (like Impulse) that won't accumulate over time like ForceMode.Force does

nocturne parcel
#

I see.

slender nymph
#

and this is really because they don't factor in deltaTime when applying the force and just apply it all at once. though if you plan to use it multiple times on the same object, it would be recommended to do it in FixedUpdate (or at least on a fixed timestep) rather than every frame

nocturne parcel
#

One thing I noticed when using AddForce (default mode)

#

Was that if I turned off gravity, it would make the object move forever even when limiting its velocity and stopping applying the force

#

I had to increase drag by a lot

#

(it moves forever but veeery slowly)

slender nymph
#

with no drag and no friction on the material that is the expected behavior. you have to have some sort of drag or opposing force to make it stop

nocturne parcel
#

Drag is applied opposite to the force, right?

#

So how can gravity work like drag for that when it is only applied down?

#

If moving to the side

#

for example

#

Anyways I think this is offtopic lol

#

sorry

open idol
#

Yesterday I saw a student creating a game and realising that the camera light, left a trail behind the moving shape. By chance, it gave a better 3D feel to the shape of the moving character.

rich adder
dusk lantern
#

i think hes asking for a replication

modest linden
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShootingTrigger : MonoBehaviour
{
public PeaSpawner ps;
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    
}
void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Zombie")
    {
        Debug.Log("Enemy in lane!", this);
        this.ps.Shooting = (true);
    }
}
void OnTriggerExit2D(Collider2D other)
{
        Debug.Log("Enemy out of lane!", this);
        this.ps.Shooting = (false);
}

}
so this script is working weird and the ontriggeerexit keeps hapening so i dont know dispite it not exiting

north kiln
#

You only check the tag in Enter, which seems odd.
Also you should use CompareTag, not equality

modest linden
#

ping back

modest linden
north kiln
modest linden
north kiln
#

No

modest linden
#

ok

devout flume
modest linden
#

i set the collision detecting to continus

modest linden
sick jay
#

which version of calculating the b vector would be more efficient? whats the best way for a new programmer to know what would be more or less costly? this is going to be run by a lot of Segments at the same time so i need it to be as efficient as possible

teal viper
sick jay
# teal viper There's not gonna be much difference if at all. A word of advice: don't get int...

I'm realizing as I start this new project is probably not a great way to do it. I'm trying to find some sort of code that can allow players to place their own tubes and wires anywhere they want in space, then have it calculate how many 'segments' of tube/wire are needed to complete this to get a cost for the total amount and to calculate how it should lay across the ground when placed

#

I'm trying to think of a better way to design it, but I want players to have full control over where pipes/tubes/wires are in the play araea

teal viper
#

As for the actual implementation, there's not much I can say, as I don't know how you have it setup right now.

open idol
# rich adder Camera light ? what is the exact question ?

Sorry,... that was a random comment. I was reading the previous comments regarding gravity and remembered the light effect following this game character.
I'll explain it better after asking the student how was he dealing with gravity, that causes this "light teail" effect.
Cheers.

nocturne kayak
#

Is there a way to do a "cone" cast?

frosty hound
#

No, casting only works with primitive shapes.

#

Either calculate the angle of nearby objects or create a mesh and use a mesh collider on it

nocturne kayak
#

In that case, do you have some advice when trying to achieve something like this?

rich adder
#

dot product prob

nocturne kayak
#

I'm trying to make a selection system that's cone\frumstrum shaped

#

and selectables closer to the direct forward vector from the controller have priority selection

rich adder
nocturne kayak
#

If i had a wide angle cone, wouldn't i have to cast maybe hundreds of raycast for accuracy?

rich adder
#

how wide? I use one for mine that goes up to 270, that has about a hundred or two and its fine

#

also depends how big colliders you plan on hitting are

#

you don't technically need that , you just need a way to grab whats infront of you. Overlap and Spherecast could also work, with ray / lines is just easier to account for narrow angle / hits from the origin point

dusky tusk
#

why is it when i code and then save it, when i go back to unity editor it says completing domain or something, how do i turn it off?

rich adder
#

You can toggle it of in the preferences iirc

nocturne kayak
#

Why would you want to do that?

nocturne kayak
# rich adder

I might give that a try, but it feels like there might be a simpler way

dusky tusk
nocturne kayak
#

I suppose not

rich adder
nocturne kayak
#

since that's the process of actually getting your code in the engine

rich adder
nocturne kayak
#

i guess you could that manually

rich adder
#

your code has to be turned into machine code

dusky tusk
#

i mean i save frequently when i write code so it is such a hassle waiting for that popup to finsh

rich adder
#

if you save frequenetly and are coding in IDE, why even go back to the Unity Editor, I just stay in IDE until I need to link stuff in inspector n setup

#

its nt like it blocks IDE when it does that compiling

runic quartz
#

Hello all, i am trying to capture a photo from the player's device (mobile, front camera) and save it as a png. I have been searching through the documentation and haven't been able to understand. Can somebody help me through this? Thanks!

zenith vine
#

is there a way to cancel the Invoke() fucntion from happening once you call it

runic quartz
rich adder
zenith vine
#

okay thanks

dusky tusk
#

how would i check if the gameobject has a tag x

rich adder
dusky tusk
#

i did, and i found out how

verbal dome
zenith vine
#

im not using InvokeReapeating so i dont think that'll work

small gyro
#

Hi everyone! I am still new but I know unity is having a Black Friday sale. Anything that is useful that I should have. Thank you!

verbal dome
burnt vapor
#

(Even questions about nice coding libraries 😄)

small gyro
#

Sorry I thought this was unity talk channel I must of changed it without noticing. Thank you!

zenith vine
verbal dome
#

Cancels all Invoke calls on this MonoBehaviour.
Sounds straightforward to me

#

It should also work with InvokeRepeating though

#

Note that Invoke is a bit of a dated way of doing this stuff so coroutines/async/awaitables are an option

zenith vine
verbal dome
#

I see, well, try it

pliant abyss
#

EasyVector Lerping

lilac crow
#

Hello Guys!
im following a Toturial and there is a Problem.
as you know FindObjectsOfType has been depricated and the other methods dont get an argument or cant be used this way.
any idea how to fix this?

cs IEnumerable<IDataPersistence> dataPersistences = FindObjectsOfType<MonoBehaviour>().OfType<IDataPersistence>();
torpid mulch
#

Hey Guys, I'm trying to figure out why my jump is not working for my 3rd person jump code. Could someone help me out? Can I paste my code here?

naive pawn
#

!code

eternal falconBOT
naive pawn
#

please do provide more info about how exactly it isn't working

torpid mulch
#

I'm currently getting a NaN on my jump velocity Vector3 whenever I press space, resulting in the character freezing wherever they are. I'm very new to this and I tried combining brackey's 3rd person movement tutorial with his jump from his first person movement tutorial but the math confuses me.
https://hastebin.com/share/jogudimohu.csharp

verbal dome
#

The doc of FindObjectsOfType also tells you what you should use instead

naive pawn
#

that doesn't really make sense

#

both hardcoding gravity and using a variable? using the existing y velocity?

torpid mulch
#

it's how Brackeys suggested to implement the jump function. For me it didn't make much sense either but I gave him the benefit of the doubt

#

I'm open to better ideas to implement jump

lilac crow
torpid mulch
#

I tried using RigidBody but I think it doesnt go well with the characterController as it stays grounded.

naive pawn
burnt vapor
#

Instead of the generic it takes the type as a parameter

#

And also it has a sort. If you don't care about it just pass none

verbal dome
#

If thats what you mean

#

Tell it if you want to find inactive objects or not

lilac crow
naive pawn
verbal dome
#

And yeah that line seems really weird

real thunder
#

the previous one is also odd

#

if velocity less than 0 it's -2... for what

radiant kraken
#

for some reason unity wont show any settings in the components tab for player movement, im following a tutorial and im pretty sure i didnt make any mistakes (sorry for the text wall)


public class PlayerMovement : MonoBehaviour
{
    private CharacterController controller;

    public float speed = 12f;
    public float gravity = -9.81f * 2;
    public float jumpHeight = 3f;

    public Transform groundCheck;
    public float groundDistance = 0.04f;
    public LayerMask groundMask;

    Vector3 velocity;

    bool isGrounded;
    bool isMoving;

    private Vector3 lastPosition = new Vector3(0f,0f,0f);
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
    //Verifica se o jogador esta pousado no chão
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
    
    //Aumenta a velocidade quando o jogador salta
        if(isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");
        float y = Input.GetAxis("Vertical");

    //Criar o vector de movimento
        Vector3 move = transform.right * x + transform.forward * z;
    
    //Movimentação do jogador
        controller.Move(move * speed * Time.deltaTime);
    
    //Verificar se o jogador pode saltar
        if (Input.GetButtonDown("Jump") && isGrounded)
    
    //Jogador salta
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }
    
    //Jogador cai
        velocity.y += gravity * Time.deltaTime;
    
    //Jogador executa o salto
        controller.Move(velocity * Time.deltaTime);

    if (lastPosition != gameObject.transform.position && isGrounded == true)
    {
        isMoving = true;
        //Poderá ser usado mais tarde
    }
    else
    {
        isMoving= false;
        //Poderá ser usado mais tarde
    }

        lastPosition = gameObject.transform.position;  
    }
}```
real thunder
#

that would help alot with finding out why you are getting NaN if you tell the string where this error appear

fickle plume
radiant kraken
#

alright let me check

#

I dont get what this means, i double checked and its the same as it is in the tutorial
Vector3 move = transform.right * x + transform.forward * z;

keen dew
#

Is the previous line also the same as in the tutorial?

radiant kraken
#

yup, the only difference there is the comment

keen dew
#

No the actual previous line, ignoring comments

radiant kraken
#

ur actually my savior lol

#

it was an y instead of a z

keen dew
#

Configure the !ide so that it'll tell you when this kind of thing happens 👇

eternal falconBOT
radiant kraken
#

alright, thanks!

sonic palm
#

Hello Everyone!

So I’m currently learning the Unity Game Engine by doing the Unity Pathways courses, it’s been a very fun process and I’m really enjoying applying all of the previous programming knowledge I’ve had in the Game Dev context. I’m currently working on my Personal Project assigned in the Junior Programmer course. I’ve decided to try and create a simple wave based 3d top down shooter, I thought this was a simple idea but it turned out to be a bit more complex than what I thought, especially in the collision department.

So I’ve currently got the Basic Gameplay down, the player can move in all directions, shoot projectiles and i’ve also added a neat little Dash mechanic to it. I’ve also added a couple of enemies that can also shoot projectiles at the player and follow him. The main problem I’m having now is that I’m using Trigger Colliders to run the code I want for the interactions between playerprojectile/enemy and vice-versa, this then makes it so the player gameobject won’t collide with the enemy gameobject’s and they’ll phase through eachother and i’ve been trying to find a way to make it so this won’t happen. After some research I think I’ll have to use the Unity Layers System to fix this but I’ve been having a hard time understanding how it works and how to apply it to my project.

Hope somebody can help and thanks in advance 🙂

modest dust
#

Is there something stopping you from having non-trigger colliders on your player and enemies?

sonic palm
modest dust
#

You can still use a trigger collider on your projectiles

#

Just switch the player and enemy colliders to non-trigger ones

#

And damage them through the projectiles OnTriggerEnter

sonic palm
#

Bruh I thought they all had to be trigger colliders for it to work ;--;

#

Thanks for the help haha

languid spire
#

btw, you do know you can have trigger and non-trigger colliders on the same object

sonic palm
modest dust
hexed terrace
#

This is a code channel and your question isn’t code related. Delete it from here and ask in the correct channel-> #📲┃ui-ux

remote tiger
#

whoops

echo crater
#

Hello, Im learning unity.
I want to know what is the equivalent of this code "OnTriggerEnter2D(Collider2D other)" but for 3d. Or is it the same but just change 2D to 3D ?

languid spire
#

just remove the 2D. Referring to the Unity documentation would have given you the answer in < 2 seconds

echo crater
#

Thanks ! This gave me an answer in 1min tho

languid spire
#

next time docs first, ask after

naive raven
#

is there something wrong with my code?

languid spire
#

you'll never know if you don't debug your code

naive raven
#

right.. okay

#

this is all that is showing. I put debugs in the main shooting mechanisms.

languid spire
#

So why not put Debugs at the START of each method to see if it is being called?

burnt vapor
#

That is, if you debugged up until the point where the issue is related to the collission not triggering

atomic holly
#

Hello,
I want to take the collider to put it in my CinemachineConfiner every time I switched scenes. Is it better that put it in the OnSceneLoaded or in the Awake() ? will there be any change ?

using Cinemachine;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SetCameraLimitation : MonoBehaviour
{
    private void OnEnable()
    {
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        if(scene.name == "_preload")
        {
            return;
        }

        //CompositeCollider2D affecter à la caméra
        CinemachineConfiner2D confiner2D = GetComponent<CinemachineConfiner2D>();
        confiner2D.m_BoundingShape2D = SingletonManager.instance.cameraLimitation;
    }

    private void OnDisable()
    {
        SceneManager.sceneLoaded -= OnSceneLoaded;
    }
}

naive raven
#

im afraid it might be my takedamage method

languid spire
#

how can it be your TakeDamage method if that is never being called?

naive raven
#

like i said, it might be. thats what i'm thinking as of right now. it might be in my OnCollisionEnter method, but everything looks fine there

languid spire
#

well it didn't look like you added debugging there to make sure it is firing

naive raven
#

im actually so dumb the bullet didnt even have the bullet script attached 🤦‍♂️ so sorry for wasting your time

languid spire
naive raven
foggy crypt
#

How do I reorder objects found by FindObjectsWithTag?
They're randomly ordered for some reason

languid spire
slender nymph
foggy crypt
slender nymph
#

then just sort the returned array like you would any other array

foggy crypt
#

how.

slender nymph
#

literally just google "sort array c#" and find out

foggy crypt
#

ok.

#

I now have a problem with this Issue
||At least one object must implement Icomparable||
My code is here:

Array.Sort(Lamps);
languid spire
#

Did you actually bother going and reading any documentation on this?

foggy crypt
rich adder
#

you need to implement IComparer

slender nymph
# foggy crypt

remember when i said to google "sort array c#" and not "sort array unity"?

languid spire
foggy crypt
#

🙂

sleek notch
#

Hi I need help. I have 2 difference textures and I need to reference the texture from another script and load it into button. Why is it not working this way?

languid spire
#

nothing there loads a texture into a button

sleek notch
#

sorry I'm dumb

celest flax
#

This code goes through the list inputList and if a value is greater than the latest value in the stack substack , it moves the value from the list to the stack. I'm just curious if either of these two methods, the while or foreach loop, is at all more efficient than the other:

while(i < inputList.Count)
{
    if (inputList[i] > substack.Peek())
    {
        substack.Push(inputList[i]);
        inputList.RemoveAt(i);
    }
    else i++;
}

foreach (Sphere sp in inputList)
{
    if (sp >= substack.Peek())
    {
        substack.Push(sp);
        inputList.Remove(sp);
    }
}```
languid spire
#

you cannot remove in a foreach

celest flax
#

Why not? Is it the same problem as if you try to use a for loop?

languid spire
#

no. you cannot modify a collection you are iterating over with foreach

celest flax
#

Oh I see, thanks

languid spire
#

btw, neither will work, both will throw exceptions

daring heath
#

does anyone know how to constrain a player's movement to a spline? so i can click somewhere on the screen, it takes the x value, and moves to the nearest point on the spline?

#

trying to use this but can't figure it out

languid spire
#

that's because the Evaluate method doesn't do that

daring heath
languid spire
#

that would depend on the spline, you could walk it or binary chop it

daring heath
#

how do you mean, and what about the spline does it depend on?

languid spire
#

the shape, binary chop would not work on a spline which is very curved

daring heath
#

could you elaborate? these terms are not familiar to me

languid spire
#

walking the spline means starting at t=0 and then looping until t=1 evaluating the position as you go and saving the one you want.
binary chopping the spline is starting in the middle and moving up or down by 50% of the remaining length until you find the position you want

frank zealot
#

Hello, I was trying to smoothly rotate my FPS camera using Mathf.SmoothDampAngle function to fix the little jittering happening when rotating my camera on a FPS controller. I have been trying to implement it for some time and I can't figure out how am I supposed to do it this way or another?

This is the base code in the update function
private float rotationX;

        rotationX -= modifiedDelta.y;
        rotationX = Mathf.Clamp(rotationX, minY, maxY);
        

        camera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0f);
        transform.rotation *= Quaternion.Euler(0, modifiedDelta.x, 0);```
wintry quarry
#

Certainly multiplying the mouse input directly with deltatime is wrong

#

Mouse delta is already framerate independent, since it's telling you the actual mouse delta for this frame

devout flume
#

Would you rather do x == null or x is null?

slender nymph
#

second is not going to work correctly with types that derive from UnityEngine.Object, you have to use the == operator with those because otherwise they will throw an exception if they are "null" (ie destroyed) but the variable hasn't been explicitly assigned null because unity has overridden the == operator to check for destroyed objects but it is not possible to override the is operator to do that

devout flume
#

Ok that makes a lot of sense, thank you for the very detailed answer 🙏🏻

shell sorrel
#

yeah in the case of regular C# the "is" one is fine but anything involving UnityEngine.Object derived stuff yeah make sure you are hitting the equality operator

#

same goes for ?. and ?? which also skip it so should not be used on UnityEngine.Object stuff

devout flume
#

So let's say I do

GameObject g;
g?.Method()

would not work since GameObject inherits from UnityEngine.Object

shell sorrel
#

correct

#

same for scriptable objects, and all component types

#

there are many cases where as far as the engine is concerned a object is destroyed but to C# its not null

#

checking via the equality operator lets unity use its own logic here instead of doing a real null check

#

its one of the larger gotcha's of unity, seen it hit newbies and experienced programmers hard too

runic lance
#

and it's always fun when you're working with interfaces and end up checking a MonoBehaviour for null...

devout flume
#

Actually that's exactly how it works in ROBLOX as well. The variable itself isn't dereferenced, yet the instance pointed by it had Destroy() called on itself, which makes it internally unusable. Hence why non-overloaded operators won't behave properly

shell sorrel
devout flume
#

Here it's more noticeable definitely

wintry quarry
#

I.e. it would still call the method on a destroyed object

shell sorrel
#

i was not going to split hairs on that one, generally best practice is to always use equality operator on UnityEngine.Object

#

but yeah the case given would work since its real null since its never been given a value

devout flume
#

In ROBLOX you would get somewhat yelled at depending on what you want to do. You can still modify most of the properties of the implicit object for sure, no error whatsoever

shell sorrel
#

you can see the difference in the reported exception as well

#

NullReferenceException vs MissingReferenceException

devout flume
#

Gotcha, thanks a lot as well for your time

shell sorrel
#

the somewhat related gotcha around this, is how Destroy works as well

#

it does not do the work immediately, but does it end of frame

jade zenith
#

I'm trying to make a sprite walk, and i'm getting "identifier expected" error (and if there's a way to differentiate between pressing, and holding a key please inform me

{
    if (Input.GetKeyDown(KeyCode.RightArrow) == true)
    {
        myrigidbody.Velocity = Vector1.(1,0);

    }
slender nymph
#

make sure that your !IDE is configured

eternal falconBOT
jade zenith
#

thank you

slender nymph
#

visual studio is the better one. vs code is the worse one

#

you just need to configure it

jade zenith
#

like this?

slender nymph
#

that is one step of it, yes

zenith vine
#

why can i make something that when my code is started is equal to null but then if i try to set it equal to null during runtime it doesnt work right

short hazel
zenith vine
short hazel
#

You log target right before setting a new value into it, you should log right after so you get an up-to-date value displayed in the console

#

Also log inside both OnTrigger* methods, make sure you don't enter the trigger right after exiting it

zenith vine
#

thank you so much for your help

#

it turns out im just an idiot

#

and didnt set the script that EnemyMovement was supposed to look in for the check_target() return statement

#

so the Null exception error was from there being no script for the code to get check_target() from

short hazel
#

You had an exception? Should have mentioned that in the first place

#

But glad it's fixed

oblique vortex
#

Does anyone know why some of the "enemies" are sometimes being destroyed even when they are far from the collider? And this only happens when the "sword" is active, the script is simple just to make the rectangle rotate around a gameobject

steep rose
short hazel
steep rose
short hazel
#

Should be on a script either on the enemy or the sword

steep rose
eternal falconBOT
short hazel
#

At the start of the video a pair of enemies top left touch eachother and get destroyed

oblique vortex
oblique vortex
plucky copper
#

How do I create a Serialized Field that I can use to say "This is the next scene I want to load"?

Build Index feels absolutely dirty and error prone (however I can work around this if it is truly the only way by means of a GameConstants.cs file).

plucky copper
slender nymph
plucky copper
#

Interesting.

terse raven
#

Im using the new input system. How do I make a button only fire when in the frame which it is pressed. Seems like whatever settings I use I get continuous presses.

astral citrus
#

Hi. I used "button" action type for this. In input configuration.

terse raven
#

Yes but if I hold the button every frame I get acknowledgement that the key is held. I want it so it fires once from when I first press it

alpine fjord
#

To get around that, I added a "intervalBetweenButtonPresses" variable.


if (button is pressed and intervalBetweenButtonPresses is <= 0)
{
do this action
intervalBetweenButtonPresses = 1f
}```

This way the button action will only occur once a second.
#

If there's a better way, I'd like to know.

oblique vortex
#

Is it a demerit to use gpt chat to help you make some scripts for your game?

alpine fjord
#

I wouldn't trust any code chatgpt gives you.

steep rose
#

it will do you more harm than good

terse raven
terse raven
steep rose
astral citrus
alpine fjord
rich adder
#

boilerplate can be acceptable if you give precise instructions & can verify the validity

cosmic dagger
steep rose
#

A stray projectile which may be a tomato will fly in your general direction if you use chatgpt for writing you code

oblique vortex
# rich adder yes

I learned Java the hard way, but I confess that sometimes I'm too lazy to read the Unity documentation and I ask for tips on how to do some things in the GPT chat.

rich adder
cosmic dagger
#

i use copilot/gemini for my codebase. it's great for documentation . . .

open vine
#

Hey, i'm thinking of making my player a state machine, and I was wondering what parts of it are needed to be in different states? Is it just movement that should be tied down to different states like grounded, swimming, airborn, etc. or should i have an attacking, rolling, interacting state, etc as well?

spark sinew
#

hi y'all, I am totally a newbie on all this, but I am unable to program some text display. I would like to make an app that has a HUD like in terminator or robocop (very simple HUD with just text)

#

it is for a Meta Quest 3. I was able to make an app that displays just a cube, but I am unable to make something that would display text that remains in the FOV

sterile radish
cosmic dagger
cosmic dagger
sterile radish
cosmic dagger
sterile radish
# cosmic dagger then you need to look in your code where `flags` is used to check when the value...

hi, i've figured out that in this script, it debugs the inspector size of the array where ive commented.
https://hatebin.com/tykhimtyik

so it seems like that the Flags from PlayerData is a different value from flags and overrides it (right here: https://hatebin.com/libszevvat). is there way to reset both of both of these arrays and then set them to each other? i think the core of this problem arose when i was testing both of these arrays and did a few runtime shenanigans on Flags which caused it to override the GameManager.flags array

NVM ITS SOLVED NOW. thank you for your help!! ^ ^

tender breach
#

I'm not sure if this is the right channel, but is it possible to save assets you made in unity for example, sprites?

#

I forgot to mention during runtime.

fickle plume
tender breach
#

Yes. You can save them in the editor, but not during runtime. I only ask because I'm making art software in unity.

fickle plume
#

Unity 6 has entire class dedicated to conversion to different formats, it's in the manual.

#

ImageConversion

tender breach
#

I'm also using it as a video editor.

tender breach
fickle plume
#

It even has an example of how to use IO library to write to file right there.

errant pilot
#

Guys I have an object I want it to go to a defined position parabolically how can I do that ive been trying for 4 days i can't do kt

teal viper
teal viper
#

In 2d too