#💻┃code-beginner

1 messages · Page 712 of 1

earnest wind
#

wait

#

actually it wont what if user needs 0

wintry quarry
#

not sure I'm following this part

earnest wind
#

will come back tommorow to this mess

earnest wind
#

if its 0, it doesnt serialize

#

even if its in list

#

so i get lists like this

#

because alpha is 1 by default

#

but a float by default is 0

#

i dont know how to override the alpha to 1 inside the list itself

wintry quarry
#

I'm imagining basically (psuedocode):

serialize() {
  for (i from 0 to defaultarray.length) {
    if (myData[i] != defaultArray[i]) {
      writeOverrride(i, myData[i]);
    }
  }
}

deserialize() {
  deserializedArray = defaultArray;
  for (override in overrides) {
    deserializedArray[override.index] = override.value;
   }
}```
earnest wind
#

and we could have some lists that are like this

#

yeah my brain isnt braining right now

#

im looking at this wall of text and i dont understand how i could make this

#

i understand how it would work

#

but dont know how to make the serialize part in the newsoft json

#

im not trying to make my own serializer right now notlikethis

earnest wind
#

ah, i understand now

wintry quarry
#

readjson == deserialize
writejson == serialize

#

I do wish their example was a little more in depth

earnest wind
#

yeah its just one example lol, but still i understand, will implement tommorow, thanks

kindred path
#

Do ya'll know why my dash code isnt working, Ive looked through it and for the life of me I can'tfigure out whats wrong

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

public class PlayerMovement : MonoBehaviour
{

    public float moveSpeed;
    public Rigidbody2D rb;
    private Vector2 moveDir;

    private float activeSpeed;
    public float dashSpeed;

    public float dashLength = 0.5f, dashCooldown = 1f;

    private float dashCounter;
    private float dashCoolCounter;
    // Update is called once per frame
    private void Start()
    {
        activeSpeed = moveSpeed;
    }
    void Update()
    {
        ProcessInputs();
    }
    private void FixedUpdate()
    {
        Move();
    }
    void ProcessInputs()
    {
        float moveX = Input.GetAxisRaw("Horizontal");
        float moveY = Input.GetAxisRaw("Vertical");
        moveDir = new Vector2(moveX, moveY).normalized;

        if (Input.GetButtonDown("Dash"))
        {
            print("success");
            if (dashCoolCounter <= 0 && dashCounter <= 0)
            {
                activeSpeed = dashSpeed;
                dashCounter = dashLength;
            }
        }
        if (dashCounter > 0)
        {
            dashCounter -= Time.deltaTime;

            if (dashCoolCounter <= 0)
            {
                activeSpeed = moveSpeed;
                dashCoolCounter = dashCooldown;
            }
        }
        if (dashCoolCounter > 0)
        {
            dashCoolCounter -= Time.deltaTime;
        }
    }
        void Move()
        {
            rb.velocity = new Vector2(moveDir.x * activeSpeed, moveDir.y * activeSpeed);
        }
    
}
rich adder
#

that print("success"); is kinda useless

#

you need more and preferably print actual values

kindred path
#

Yeah I was just checking that my Input manager was working cause I didnt know

kindred path
#

I was using the wrong variable 😐

unkempt kettle
#

Hey, I got a question about scriptable objects

Context
I'm making a magic system in my game that you can only have one active spell in your spellbook and need to change it frequently. I though about making it with scriptable objects, but I also want them to level up in certain points of the game (altering the scriptable object).

Question
How can I write values into my scriptable objects?
In this case, I want to be able to change my Spell Level from 1 -> 2 and vice-versa (Ex: When getting an upgrade / Loading a save file)

rough granite
#

also whoops misclicked

unkempt kettle
sour fulcrum
#

There's two routes you can go, with the first being more ideal so i'll elaborate on that more than the other

  1. You basically make a "live" version of your spell class and have a sibling-esque relationship with your scriptableobjects. Here you would use your scriptableobject to give the "live" version of the class it's default values, then modify that instance of the class how you need

  2. Runtime creation of scriptableobjects

unkempt kettle
#

I'll look into it, thank you very much 🫂

rough granite
unkempt kettle
sour fulcrum
#

Though as you might be already cautious about direct changes to scriptableobject assets at runtime will not reset when you exit play mode

rough granite
sour fulcrum
#

I mean yeah theres no way they could do that

#

thats just how assets work

rough granite
#

they could just reset them in unity after though

#

at least have it consistent you know

sour fulcrum
#

that would be inconsistent with how assets are treated in unity tho

rough granite
#

i mean i guess :/

weak roost
#

Hi there,
how can I ensure that monobehavior GUIs can register for events from controllers that are plain C# classes without being null? Calling a new Controller in awake and then registering for the event in onenable/ondisable always returns a null pointer because the instance is created too late.

How do you solve such a general problem?

teal viper
hot wadi
#

About DontDestroyObject scripts, do I have to assign scene-specific references during runtime?

teal viper
naive pawn
#

do you mean DontDestroyOnLoad

hot wadi
#

DontDestroyOnLoad objects persists between scenes, and there are objects that only exist in certain scenes.
I know can manually find each of them in the script, but it feels tedious and possibly slow the game if it's large enough
So I'm looking for alternative if there is one.

teal viper
glossy turtle
#

does anyone ever solved gradlew.bat error when resolving android dependencies?

lethal meadow
#

!code

eternal falconBOT
lethal meadow
#

how can i add normal mapping for my textures?

#

seems easy to but i dont know

worthy veldt
#

i just found out i can't inherit from plain class, so currently my banana can technically contains items like my pouch because i just jammed it all in Item class. no problem so far, but what is the correct way, make multiple classes ?

teal viper
worthy veldt
#

there is an error and from google ai it said

#

In Unity, you can inherit from a custom Item class, but issues can arise with serialization and editor functionality if Item is a plain C# class and not derived from MonoBehaviour or ScriptableObject.

teal viper
lethal meadow
teal viper
lethal meadow
#

how do i use it then

#

or would it be better to make my own lighting system

#

i made an engine a while ago and the lighting was definitely very poor

#

im not that good with shaders

teal viper
teal viper
sour fulcrum
teal viper
lethal meadow
teal viper
#

Because it's gonna be a pain in the ass, especially if you don't have experience.

lethal meadow
#

and i dont think you can do that

#

i'd definitely use a shader graph though

teal viper
#

But currently I don't see anything that is not implementable in a shader graph by default.

worthy veldt
# teal viper Well, this doesn't really say anything specific. Plain classes can be serialized...

arent plain class not inheriting from anything by definition ?, it did said

"Use [SerializeReference] for polymorphic serialization of plain C# classes. This attribute allows Unity to correctly serialize and deserialize derived types within a collection or field, preserving their specific data. You might also need a custom editor to manage adding different derived types in the Inspector."

but im afraid ill break my stuff with current setup. maybe ill delve into it when im free

sour fulcrum
#

as a statement the text that ai provided in this specific scenario is not wrong

#

but as an answer to your question its pretty abyssal

#

base class usage in unity is extremely common and unity supports it explicitly

#

like anything in unity, things can go wrong if you do it wrong

teal viper
sour fulcrum
#

and because its not a monobehaviour or scriptableobject, they way you treat them is abit different

teal viper
worthy veldt
#

yea i just test with empty new plain classes inheriting works fine. ill look into my prob

worthy veldt
#

so.. my derived class needs constructor that supports my base class, it has to be written in certain way..

#

i didnt know the syntax alright

#

but i already made my container banana, ill refactor and change it later..

mystic bay
#

hi

#

how to start in unity? i want make tornado game.

naive pawn
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

mystic bay
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

glossy turtle
#

does anyone knew how to disco dance a text with code in unity

junior ridge
#

I want to create Flappy Bird in Unity but I can not handle Jump with new input system. Can someone help?

echo geode
#

hello guys

#

i had a question i found this online tutorial for C# since i want to learn it instead of relying on ai 24/7 and wanted to know if what this tutorial teaches me will only be applicatble to websites and etc or help me in unity too is there a difference between unity C# and normal C#

sour fulcrum
#

there's some differences in how you specifically use it but overall you learn the same stuff

echo geode
#

https://www.youtube.com/watch?v=r3CExhZgZV8&list=PLZPZq0r_RZOPNy28FDBys3GVP2LiaIyP_

i am following this tutorial seems pretty old(4 years ago) but looks promising

C# tutorial for beginners

#C# #tutorial #beginners

⭐️Time Stamps⭐️
00:00:00 intro
00:00:48 download Microsoft Visual Community
00:01:41 new project
00:01:59 change IDE font size
00:02:24 compile and run program
00:02:38 Main method
00:03:35 Console.WriteLine();
00:04:27 change Console font
00:05:18 Console.Beep();
00:05:40 conclusion...

▶ Play video
alpine temple
#

will it work if i build the game?

#

or is something wrong with the script

keen dew
#

!code

eternal falconBOT
keen dew
#

If it doesn't work in the editor then it won't work in the build either

#

the code never saves anything to playerprefs

alpine temple
keen dew
#

No. You're not telling it what to save and where

#

SetFloat is for saving floats to playerprefs

#
bestTimeL1 = quickReload.timerTime;
if (quickReload.timerTime <= bestTimeL1 || bestTimeL1 == 0)

this is also wrong, if you've just set the both variables to equal each other then the condition on the next line where it checks if they're equal will always be true

rough granite
alpine temple
naive pawn
glad fjord
#

Can anyone help me with understanding what the use of ADDING Time.deltaTime is, please?
I understand why we would multiply by it, but why would one add it to make a timer for example? How would that make any sense?

waxen glacier
#

So i've added a RayCast to try and get the angle of a surface so I can modify movement on slopes, but the problem is that i'm getting the angle of the raycast relative to the surface normal instead of the actual incline of the terrain, and I don't know what I should write to get that angle.
https://paste.ofcode.org/daj5pGjCJ427y7r5Djvc9g

As a visual example to make myself clearer, the blue angle is what I get with my current code, the red line is the RayCast and the green line is the ground normal. I want to be able to get the value of the pink angle instead, but I don't know where to start.

keen dew
#

The blue and pink angles are the same

alpine temple
#

im doing stuff like this to save BestTimes for different lvls is there a simpler way to do this?

naive plank
#

How would I go about moving on low poly terrain, still following the mesh but without that bumpy, slow, and getting stuck feeling?

grand snow
#

custom collision mesh thats better?

#

also split this into sections so you can use occlusion culling

wintry quarry
naive pawn
naive plank
# grand snow custom collision mesh thats better?

I've been thinking about that, whats holding me back is, the player model, im using a capsule collider right now and have foot IK "snapping" the feet to the ground, then I would need to layer the ray casts, that would be fine, but I somehow need to adjust the collider hight too otherwise the distance to the ground is too big making the foot float instead

wintry quarry
glad fjord
naive pawn
#

it doesn't

#

you do

#

you decide how to interpret the values

glad fjord
grand snow
#

good lord its up to YOU

alpine temple
glad fjord
grand snow
#

Time.deltaTime is seconds so if you use as is then its all seconds

glad fjord
#

well here we go

naive pawn
#

3 can be 3 seconds, 3 frames, 3 meters, 3 meters per second, etc

#

it's all up to how it's used

glad fjord
#

so in order to treat them as seconds, I need to add seconds to them?

grand snow
glad fjord
#

I have read this

naive pawn
glad fjord
#

I understand that it might seem basic to you guys but it is not to me. I don't understand how UNITY can think of them as seconds

naive pawn
#

and use them accordingly
setting or adding a value? make sure it's in seconds
passing it as an argument to something else? make sure that thing expects seconds

naive pawn
#

the language just does not have a concept of units

#

this exists entirely outside the code

grand snow
#
float timerInSeconds = 0f;
void Update()
{
  timerInSeconds += Time.deltaTime;
}
#

oh look its counting real time in seconds because the source value is the delta for that frame in seconds

naive pawn
#

this is how you treat a variable as seconds

float time;
Debug.Log($"time: {time} seconds");
#

it's all about how you, the developer, intend it

#

it does say "seconds" in the code, but that's inside the string. unity and c# don't care about that, that's for your eyes, the developer

glad fjord
#

the guy in the tutorial I'm watching did not specify any number. he simply wrote timer += timer + Time.deltaTime;
AND he said the timer would count 2 SECONDS until it resets
so how does this make any sense?

naive pawn
#

calm down, you're trying to find a link where there isn't one

glad fjord
#

he did write public foat spawnRate = 2 and private float timer = 0 but why would those be counted as seconds then

naive pawn
#

because he said so

#

that's all it is

glad fjord
#

hahahaha I don't get it

grand snow
#
float timerInSeconds = 0f;
void Update()
{
  timerInSeconds += Time.deltaTime;

  if(timerInSeconds >= 2f)
  {
    DoSpecialThing();
    timerInSeconds = 0f;
  }
}
naive pawn
#

unity is not sentient - it does not think about seconds

glad fjord
#

but then how does it count 2 SECONDS before it resets

grand snow
#

Indeed. Its our logic that makes things happen when we want

glad fjord
#

if he didn't put in any math

grand snow
#

Look at my example

naive pawn
#

Time.deltaTime is just some random number, but unity devs defined it to be seconds
so when you set a variable to that value, it is also in seconds

alpine temple
grand snow
#

!code

eternal falconBOT
naive pawn
#

when you compare it to other values, those are also in seconds (otherwise it wouldn't make sense)

glad fjord
naive pawn
#

no, it just means it's a float

grand snow
#

its a float literal

alpine temple
#

'''cs
//buh
'''

grand snow
#

the number 2 as a float

glad fjord
glad fjord
quick fractal
alpine temple
#
buh
#

cool thanks

naive pawn
#

perhaps throw out "seconds" for a bit, you might be thinking too narrowly

grand snow
grand snow
#

Then you should get why we use it to count time passing in this way

glad fjord
#

I just find it odd that simply relating a random number to something counted in seconds automatically makes it count as seconds

#

but if that's what it is that's fine I get it now

grand snow
#

because your understanding is flawed, the value we are using is the frame DELTA

#

There is an alternate way to check for passed time that may make more sense to you:

float lastTime = Time.time;

void Update()
{
  if(lastTime + 2f < Time.time)
  {
    DoSpecialThing();
    lastTime = Time.time;
  }
}
#

this does a thing every 2 seconds

naive pawn
glad fjord
#

the last frame and the current one?

grand snow
#

This works because each Update() Time.time is different as its being advanced by unity for us

glad fjord
naive pawn
naive pawn
glad fjord
#

he just never specificed that Time.deltaTime was counted as seconds tbh that's the key thing

quick fractal
#

There's a timer example there that explains it

glad fjord
#

but 2 times 0.0something won't make 2 seconds would it now?

naive pawn
#

not sure where you got the "2 times" part from?

glad fjord
#

how does he end up with a 2 seconds timer

waxen glacier
glad fjord
#

well this

naive pawn
#

there's no multiplication there

glad fjord
#

hum you're right I messed that up

#

so timer is equals to timer + Time.deltaTime, but that doesn't equal to 2 seconds tho

naive pawn
#

but that happens a lot of times

#

timer accumulates the deltaTime

glad fjord
#

tho he did say the timer would be 2 seconds

#

oh

wintry quarry
grand snow
#

we are going in CIRCLES AAAAAA

#

Try out the examples and witness them work and deal with it

naive pawn
# naive pawn `timer` *accumulates* the deltaTime

suppose a consistent deltaTime of 0.2 (aka 5 fps)```
frame 0: timer = 0.0
frame 1: timer = 0.0 + 0.2 = 0.2
frame 2: timer = 0.2 + 0.2 = 0.4
frame 3: timer = 0.4 + 0.2 = 0.6
frame 4: timer = 0.6 + 0.2 = 0.8
frame 5: timer = 0.8 + 0.2 = 1.0

glad fjord
#

I think I get it: it ends up being a 2 seconds timer because it says that until timer is at least equal to spawnRate, which is 2, then it will reset.
so spawnRate also ends up being counted as seconds in that situation?

wintry quarry
#

note that the computer doesn't actually "know" anything. it simply performs the commands you give it

naive pawn
#
float lastTime;
void Update() {
  float deltaTime = Time.time - lastTime;
  Debug.Log($"{deltaTime} seconds elapsed");
  lastTime = Time.time;
}
``````cs
float lastPosition;
void Update() {
  float deltaPosition = transform.position.x - lastPosition;
  Debug.Log($"{deltaPosition} meters traveled");
  lastPosition = transform.position.x;
}
```these 2 snippets are equivalent if you just look at the numbers. we can analyze that the first is using seconds and the second is using meters because of what other values it's using - ones that are defined as those units
but sometimes you don't have values that have predefined units, you might specify those units yourself - and that's all in how you decide to treat them, not related to how it's written at all
glad fjord
#

yeah I think I get that

#

I'm just not fully sure about how it ends up being a 2 seconds timer, in relation to the spawnRate

naive pawn
#

it's counting in time

#

if the counted time is more than spawnRate, do the thing

wintry quarry
naive pawn
#

Time.deltaTime is in seconds and spawnRate is 2, so it happens to be 2 seconds
nothing about the logic thinks about seconds

glad fjord
#

because it couldn't define that timer is inferior or not to spawnRate otherwise

naive pawn
#

since there's no conversion factor, yeah

glad fjord
#

ok

naive pawn
#

you could have it checking against spawnRate * 60 and then it'd be treating spawnRate as minutes

glad fjord
#

it's all in relation to something then

naive pawn
#

it's usually thought of in the other way though

grand snow
naive pawn
#

you decide that spawnRate is in seconds

glad fjord
#

almost there

naive pawn
#

then if you end up comparing spawnRate to a value in minutes, that's just a mistake - it doesn't redefine spawnRate

glad fjord
#

now last thing: I'm getting confused about how "timer = timer + Time.deltaTime;" doesn't end up being 0 = 0 + Time.deltaTime

naive pawn
#

the left side isn't 0

glad fjord
#

since we defined that timer is equal to 0 before

naive pawn
#

= is an assignment

glad fjord
#

yeah I assumed it wasn't but why

#

oh

naive pawn
#

it's setting the variable timer to be the value timer plus deltaTime

wintry quarry
glad fjord
#

so how exactly does Unity treat the left timer as something to get value from the right part, instead of treating it as 0?

wintry quarry
#

0 + .015 gives you 0.015

naive pawn
#

this is how c# works

wintry quarry
#

a = 5; makes a be 5

naive pawn
#

= takes the value of the right side and puts it into the variable on the left

wintry quarry
#

it doesn't matter what a was before

naive pawn
#

just like how float timer = 0; was before

#

if you took the left side as a value that just wouldn't work, since timer didn't exist before that point

glad fjord
#

was missing this info

wintry quarry
#

so this was a.. you didn't understand how = works in programming?

naive pawn
#

that's basic c#, so.. you're definitely in too deep for your level of understanding lol

balmy vortex
#

why does the stuff in void Start() not carry over to the statement in void Update()?

wintry quarry
eternal falconBOT
glad fjord
#

so thank you guys, it felt like my dad screaming at me for not understanding math all over again but it was worth it

balmy vortex
naive pawn
frosty hound
#

Because you're making new variables inside of an if statement. Think of the { } as "walls". If you make something inside of it, nothing outside of it will know of its existence.

#

If you want variables which are accessible throughout your script, put them outside these functions, at the top (but inside your class)

polar acorn
# balmy vortex well why does this not work then?

To be more precise, when you declare a variable in a scope it is local to that scope only. Praetor was likely not wanting to introduce the concept of scopes to someone who hasn't even configured their IDE and is likely just starting

#

variables exist until they hit a }

wintry quarry
#

Using {} defines scopes

buoyant haven
#

Hello everyone. I have a material with shaderGraph shader which just outputs a simple noise. I want to render this material into renderTexture, but it is not working. I created a script which does
Graphics.Blit(null, renderTexture, material);
then I assign this texture to a RawImage to see results. Maybe I need to do something with UVs. How should I do rendering of custom material into square render texture?

grand snow
#

Try normal UV input instead of screen pos.
And go to rendering to ask such questions

#

Wrong channel

naive pawn
tidal patrol
#

Thanks!

buoyant haven
balmy vortex
primal trench
#
        {
            if (!IsGrounded)
            {
                return;
            }

            float time = 1;

            while (time <= 1)
            {
                
                PlayerCamera.transform.localPosition = Vector3.Lerp(PlayerCamera.transform.localPosition, new Vector3(0, -0.346f, 0), time);

                time -= Time.deltaTime;
                Debug.Log(time);
            }
        }

why's it just snap directly to the bottom position

#

ignore the spacing discord messed it up

ivory bobcat
primal trench
ivory bobcat
#

Well, you're not doing proper linear interpolation so I would advise you first to consider that. Otherwise, this likely all happens instantly as it doesn't seem to be yielding control

polar acorn
primal trench
#

oh. how do i fix both those issues?

ivory bobcat
#

Depends.

polar acorn
#

Don't use a while loop and have the timer tick down in Update

primal trench
ivory bobcat
#

You should show more !code if you're wanting advice. Otherwise as suggested, process the lerp in Update without the loop

eternal falconBOT
primal trench
ivory bobcat
#

Right now, the function will complete the loop before exiting the function.

hot wadi
#

Start is called at the beginning of an object when a new scene is loaded, right?

grand snow
#

called once after a monobehaviour is created and enabled

#

so that also happens to occur when a new scene opens

hot wadi
#

Oh right, but not really for a singleton

grand snow
#

not relevent, if the component already had Start() called it wont happen again

hot wadi
#

I mean the second part

#

DontDestroyOnLoad singletons

grand snow
#

Do not confuse the two

hot wadi
#

They run one time only, so the scene loading does not call Start on them

grand snow
#

If you load a new scene, it will create gameobjects and their monobehaviours may then have Start() called because they are newly made

hot wadi
#

I get what u mean

grand snow
#

If you move one of those gameobjects do dont destroy on load, start() will NOT be called on it again

ivory bobcat
#

The objects that have been marked to not be destroyed aren't being created in the new scene so they do not call Start. They had already called Start when they were created.

hot wadi
#

So there is that

grand snow
#

If you understand then thats good case closed

obsidian fox
#

I m fairly new to Shadergraph and I want to know if its possible to add text on a texture using Shadergraph?

lunar coral
#

hello,I have an issue in my gunsystem script, the player can shoot thru walls and still hit enemies, the WhatIsEnemy layer contains walls obstacles and enemies

#

if (Physics.Raycast(fpsCam.transform.position, direction, out rayHit, range, whatIsEnemy))
{
if (rayHit.collider.CompareTag("Enemy"))
{
rayHit.collider.GetComponent<Enemy>().TakeDamage(damage);
}
else
{
Instantiate(bulletHoleGraphic, rayHit.point, Quaternion.Euler(0, 180, 0));
}

    }
ivory bobcat
#

Maybe you should check if a wall was hit first?

grand snow
lunar coral
#

I went in holiday for 15 days and it looks like I've forget everything

ivory bobcat
ivory bobcat
#

It doesn't have anything to do with stopping a raycast.

lunar coral
#

the ray hits the wall first which is in the layer, so the RayHit basically is the wall

#

which would stop the ray?

#

from going further$

#

no?

ivory bobcat
#

Check if the wall has the same layer mask

lunar coral
#

different layers but they both are referenced to the WhatIsEnemy variable

polar acorn
eternal falconBOT
ivory bobcat
lunar coral
lunar coral
polar acorn
# lunar coral

You cropped the actual relevant bit out of this screenshot

lunar coral
#

IM TOO DUMB, I created the layers, but didnt assign them to the walls and obstacles

polar acorn
lunar coral
#

which is also the reason the hit effects weren't appearing$

lunar coral
polar acorn
#

When it'd take like two seconds to check, you should just check.

I have not left the house without my phone and wallet in like ten years but you can bet that I pat my pockets every single time I leave the house before I lock the door

lunar coral
umbral bough
#

Hey, I was under the impression these 2 were supposed to be the same, with the exception of the first one ignoring the mass of the rb:

_rb.AddRelativeTorque(new(_flipRotation, 0), ForceMode.VelocityChange);
_rb.AddRelativeTorque(new(_flipRotation, 0), ForceMode.Impulse);

However, I noticed that the VelocityChange one messes up the rotation occasionally, it just feels off and is sometimes a mirror of what it should be(I flip in the opposite direction).
Is this a bug or am I misunderstanding how this works?
Please @ me and thanks in advance!

wintry quarry
#

Flipping in the opposite direction might just be a result of going too far in one direction or reaching the limits of the maximum rotation rate. It's hard to say without being privy to the exact details here

umbral bough
#

Would be nice if there was a built in way to just ignore the mass tbh, guess I'll just stick to impulse and scale with mass :/

primal trench
#
        public IEnumerator StartSlide()
        {
            if (IsGrounded)
            {
                ElapsedTime = 0;

                while (ElapsedTime < 0.1f)
                {
                    PlayerCamera.transform.localPosition = Vector3.Lerp(PlayerCamera.transform.localPosition, new Vector3(0, -0.346f, 0), ElapsedTime/0.1f);
                    ElapsedTime += Time.deltaTime;
                    yield return null;
                }
            }
        }

        public IEnumerator EndSlide()
        {
            ElapsedTime = 0;
            while (ElapsedTime < 0.1f)
            {
                PlayerCamera.transform.localPosition = Vector3.Lerp(PlayerCamera.transform.localPosition, new Vector3(0, 1.125f, 0), ElapsedTime/0.1f);
                ElapsedTime += Time.deltaTime;
                yield return null;
            }
        }

why does the players' view jitter up and down when the button is pressed quickly?

#
        void OnSprint(InputValue Value)
        {
            if (Value.isPressed)
            {
                Debug.Log("Test");
                PlayerFPController.StartCoroutine(PlayerFPController.StartSlide());
            }
            else if (!Value.isPressed)
            {
                PlayerFPController.StartCoroutine(PlayerFPController.EndSlide());
            }
        }

this is the input code

#

it's only when the button is seemingly pressed before the 0.1 second timer ends

#

the only "fix" i've found is stoppuing all coroutines in the input code, but that seems not the best, stopping the two coroutines individually doesn't work??? they're the only two coroutines.

keen dew
#

Stopping them individually does work but it's very easy to do it incorrectly

primal trench
#

for both released and pressed

keen dew
#

You need to show what you actually did for us to tell what was wrong with it

#

that does work if you do it right

primal trench
# keen dew You need to show what you actually did for us to tell what was wrong with it
        {
            if (Value.isPressed)
            {
                PlayerFPController.StopCoroutine(PlayerFPController.EndSlide());
                PlayerFPController.StopCoroutine(PlayerFPController.StartSlide());
                Debug.Log("Test");
                PlayerFPController.StartCoroutine(PlayerFPController.StartSlide());
            }
            else if (!Value.isPressed)
            {
                PlayerFPController.StopCoroutine(PlayerFPController.EndSlide());
                PlayerFPController.StopCoroutine(PlayerFPController.StartSlide());
                PlayerFPController.StartCoroutine(PlayerFPController.EndSlide());
            }
        }
#

i don't know why this wouln't work

keen dew
primal trench
west garnet
#

im making a boss battle and the boss instantiates a few minions
i made an observer pattern for the health, does anyone know how can i make each minion with their own event

keen dew
#

No, every time you call StartSlide or EndSlide it starts a new coroutine

primal trench
keen dew
#

There are instructions in the link I posted

primal trench
#

is there a way to get running couroutines?

keen dew
#

I don't quite get what you're asking

sour fulcrum
#

startcoroutine returns the coroutine value

keen dew
#

check if the variable is null before calling stopcoroutine

primal trench
# keen dew check if the variable is null before calling stopcoroutine
        {
            Coroutine EndSlideCoroutine = null;
            Coroutine StartSlideCoroutine = null;

            if (Value.isPressed)
            {
                if (StartSlideCoroutine != null)
                {
                    PlayerFPController.StopCoroutine(StartSlideCoroutine);
                }
                if (EndSlideCoroutine != null)
                {
                    PlayerFPController.StopCoroutine(EndSlideCoroutine);
                }
                StartSlideCoroutine = PlayerFPController.StartCoroutine(PlayerFPController.StartSlide());
            }
            else if (!Value.isPressed)
            {
                if (StartSlideCoroutine != null)
                {
                    PlayerFPController.StopCoroutine(StartSlideCoroutine);
                }
                if (EndSlideCoroutine != null)
                {
                    PlayerFPController.StopCoroutine(EndSlideCoroutine);
                }
                EndSlideCoroutine = PlayerFPController.StartCoroutine(PlayerFPController.EndSlide());
            }
        }```
like this? it still doesn't work
polar acorn
keen dew
#

well no because those are local variables that disappear right after the function ends (and even if they didn't they're set to null at the start, removing any coroutine that might be stored there)

polar acorn
#

So you press sprint, you set those Coroutine variables to null

#

So you are calling StopCoroutine on a null

keen dew
#

make class fields (private Coroutine EndSlideCoroutine;) outside the function

primal trench
#

i made it public and now it works :) thaks

#

one more think, when going down slopes do character controllers by default increase in speed or do i need to make that?

keen dew
#

Depends how much you want to increase the speed, the simple ones usually go faster in relation to the slope because the vertical velocity stays the same

#

(but not noticeably)

hot wadi
#

Awake() should be called first time even when an object is inactive, right?

naive pawn
primal trench
keen dew
#

You have to code the movement to that yourself anyway so in that sense you do need to make it

primal trench
uneven furnace
#

Hi, I bought Harrison Ferrone's book "Learning C# by Developing Games with Unity". Has anyone read it?

polar acorn
#

If you're looking for a specific recommendation then it's probably too late since you already bought it.
If you have a question about it you should probably just ask it

red igloo
#

I have this script where when I press esc the game should pause and the cursor should show and when you un pause it shouldn't show. the pausing works but the cursor doesn't show at all in the build version nor does it really work in the editor am I doing something wrong?

https://paste.ofcode.org/Ft94nrnMyycBecH8XpCCF

rough granite
red igloo
rough granite
red igloo
#

should I just reference the lockCursor bool from my fpsController?

rough granite
gentle bone
#

i had some similar problem .. try switching the positions.. first the visibility then the lockstate..

rough granite
gentle bone
#

yeah probably.. but as said i had some similar problem w a while ago.. it fixed my problem just swapping them around...

red igloo
#

I think I am just going to let the main menu script handle hiding/showing the cursor

primal trench
#

if I want a character that's physics based (sliding, wall jumping ect.) is it Really best to use a character controloler? is there another component or plugin that has more stuff built uin like godot's or is this really the best wy

frail hawk
#

there is the rigidbody

primal trench
#

t that

#

not reccomended for players

#

or is it fine

frail hawk
#

yes it is fine..

cosmic quail
primal trench
cosmic quail
primal trench
#

what's that?

cosmic quail
round mirage
#

Hello 🙂 i made this scriptable object but i would like to know how can i get this data in my script ?

rough granite
round mirage
wintry quarry
round mirage
#

Ohhhh like public ScriptableObject wood; ?

polar acorn
#

In this case, Item

round mirage
#

public Item wood; ?

wintry quarry
round mirage
#

and so after i can do something like wood.id ?

topaz chasm
#

should ı make my inventory system on a dont destroy on load gamemanager object to save it

frosty hound
#

No, the smarter thing would be to use a separate scene to hold objects that should persist throughout the game.

#

And then load your gameplay scenes asynchronously. That way your Root scene (or whatever you call it) that contains your inventory object and any other managers for that matter, will also be available.

west garnet
#

my boss from the game im doing spawns some minions, in the health script because i used an observer pattern i need an event, and each minion needs their own, how can i every time that a minion spawns give their own events?

civic axle
#

Hi, I am following the Junior Programmer Pathway, and I am stuck at "Lab 3 - Player Control". There is no Project Files to download, anyone know where I can get them?

keen dew
#

Doesn't look like you need to? Seems that you're supposed to make the project from scratch

civic axle
#

Oh, that explains it 🙂

round mirage
#

Hello again 🙂 i would like to change My image sprite but i think i dont get the component correctly. someone know what is wrong ? Icon = gameObject.GetComponentInChildren<Image>(); txt = gameObject.GetComponentInChildren<TextMeshPro>(); Icon.sourceImage = sprite;

frail hawk
#

create direct references instead of doing this mess

round mirage
#

but i will have to make this reference in every slots 🥲

#

does something to get a child by his name exist ?

grand snow
#

use layout groups to do horizontal/vertical/grid layout automatically

round mirage
grand snow
#

Yea what you did works but its not great

#

currently you need something like

foreach(GameObject slot in slots)
{
  slot.GetComponentInChildren<Image>().sprite = blah;
}
#

better to have

foreach(Slot slot in slots)
{
  slot.image.sprite = blah;
}
thorn kiln
#

So, for my unity pathway personal project, I wanted to make a game where you destroy cubes by jumping on the top of them, the problem I'm having though is that I don't think I've actually been taught any way to move a 3d shape towards the player other than addForce, which just seems to make the blocks very "slippy"

round mirage
grand snow
#

yea you can make a new script called "Slot" to let you reference the image and text of each slot easier!

#

then have a serialized List<Slot> slots

round mirage
#

I made this to get my child but it dont change the picture and the text 🥲

    public int id;
    public string Name;
    public Sprite sprite;
    private Image Icon;
    private TextMeshPro txt;
    private GameObject logo;
    void Awake()
    {
        logo = gameObject.transform.Find("Icon").gameObject;
        Icon = logo.GetComponent<Image>();
        txt = gameObject.GetComponentInChildren<TextMeshPro>();
    }
    void Start()
    {
        ReloadSlot();
    }

    // Update is called once per frame
    void Update()
    {

    }
    public void ReloadSlot()
    {
        txt.SetText("x" + numb.ToString());
        Icon.sprite = sprite;
    }```
frail hawk
#

is this script on each of your Slots

round mirage
#

i tried to put it on only one but yes it is supposed to be on every slots

grand snow
#

the you can just drag both in via the inspector ui

round mirage
#

ok i will try

thorn kiln
#

Hmm, I got it to not be slippy with transform.Translate, now I have the problem that it's ignoring that Ifroze it's Y axis, so now it's flying and even sinking into the ground somehow

wintry quarry
thorn kiln
#

Would it work if I just transformed the object itself?

wintry quarry
#

which object? Isn't that what you're doing?

You should back up and explain what you're trying to accomplish exactly

wintry quarry
#

if you don't want to deal with realistic momentum

thorn kiln
#

The problem is, the pathway course is asking me to design how enemies move while only having taught me transform.Traslate and AddForce

#

And I dont think either are great for my idea

wintry quarry
#

they are not

#

I'm telling you a better alternative

#

note that what you want is possible with AddForce it would just require more complex calculations than what you are probably interested in performing

#

and it would be simpler to just set the velocity directly

thorn kiln
#

That right?

#

I dont really know how to impliment velocity, so this is a bit tricky

grand snow
# thorn kiln

you can use Rigidbody.MovePosition() instead which will do velocity changes for you

wintry quarry
wintry quarry
#

MovePosition doesn't respect collisions

#

There's no good reason to use it over velocity here

#

It's really for kinematic bodies

grand snow
#

It does because its still uses velocity to move

#

but you will keep pushing into things

wintry quarry
#

It will happily put your non kinematic bodies inside of walls

#

Try it and see

grand snow
#

not what I have observed 🤔

#

oh shit is 3d and 2d different

#

ffs unity

#

my mistake I used the 2d version last

thorn kiln
#

So how would I use linear velocity to make it move towards the player

grand snow
#

set the velocity to something to go towards some position
Vector3 dir = target - self; (not normalized)

#

rb.linearVelocity = dir.normalized * multiplier

thorn kiln
grand snow
#

you may wish to clamp the magnitude of the new velocity using Vector3.ClampMagnitude() but should mostly work

thorn kiln
#

What would that accomplish? I haven't had to deal with clamp yet

bleak glacier
#

Could anyone point me in the right direction here?

I'm looking to create an inventory system, and there will be some pre-existing items that the player can add to their inventory.

However, I need to create an item system that allows to the player to create items with custom values and descriptions. I'm assuming that I'll be using structs, but beyond there I don't really know where to start. Can someone point me in the right direction?

grand snow
thorn kiln
#

Ah yeah, my look direction is normalized

#
    void Update()
    {
        Vector3 lookDirection = (player.transform.position - transform.position).normalized;

        enemyRb.linearVelocity = lookDirection * speed;
    }```
#

(Not that I actually understand what that does)

wintry quarry
rotund root
#

is there any smart way to make my 2d sprite blink repeatedly? (this is for when taking damage)
this is the method i could think of and i know it looks stupid

IEnumerator TakingDamage()
{
  while(takingDamage)
  {
    invincible = true
    defaultSprite.SetActive(ture);// ---------
    yield return new WaitForSeconds(0.5f);//-- this 4 lines repeat 3 times
    defaultSprite.SetActive(flase); //-------- not pasting them all out
    yield return new WaitForSeconds(0.5f);//-- cuz i dont want to clog the chat
    invincible = false
    takingDamge = false
  }
}
bleak glacier
wintry quarry
#

Never repeat code like this

wintry quarry
grand snow
#

le google

rotund root
thorn kiln
#

Yeah, thats the jargon answer though. I don't really understand what that means in a practical sense so I dunno how and when to implement it

wintry quarry
#

It's just the length of the line

grand snow
#

google will define all these terms for you

#

and are important to learn for working with 3d vector maths

wintry quarry
#

The point of it is to have a vector that can easily be multiplied by something (such as the speed here) to get a vector with a desired magnitude since a magnitude of 1 is the multiplicative identity value

thorn kiln
#

It's all over my head atm

polar acorn
thorn kiln
#

I'm still very beginner

grand snow
#

well when getting a direction vector its best to normalise so it makes things consistent and not change based on the distance

#

(unless we desire such an effect)

slow blaze
#
 void Update()
    {
        Vector3 target = Player.transform.position - transform.position;
        if (enemyState == STATE.Aiming)
        {

            Aiming(target);
        }
        else if (enemyState == STATE.Dashing)
        {
            Dashing(target);
        }
    }

  

    void Dashing(Vector3 target)
    {
        //logic to dashing will be implemented later
        transform.Translate(3f * Time.deltaTime, 0, 0);


    }

    private enum STATE
    {
        Aiming = 0,
        Loading = 1,
        Dashing = 2,
    }


    void Aiming(Vector3 target)
    {
        //Keep looking at the player. 
        float angle = Mathf.Atan2(target.x, target.z) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0, angle, 0);
        StartCoroutine(waitToChangeState(3f, STATE.Dashing));
    }

    IEnumerator waitToChangeState(float delay, STATE state)
    {
        yield return new WaitForSeconds(delay);
        enemyState = state;
    }```

Hey guys I want to change the enemy state based on a delay, and this is what I came up with. I don't know if the repeated calling of  (StartCoroutine(waitToChangeState(3f, STATE.Dashing));)
Will cause a problem?
Is there a better way to change states on a timer?
wintry quarry
slow blaze
wintry quarry
#

that seems like a coroutine you only would want to start when you first enter the aiming state

#

in the case of this script it seems like maybe in Start

slow blaze
#

Thing is, I will enter the aiming state again.
I haven't written it yet but after dashing, it's going to return to Aiming state

#

And it's supposed to go back and forth

#

Dash and Aim, Dash and Aim

wintry quarry
#

you would start the coroutines when you enter the states

#

it might make your code cleaner to make a function for entering a state

#

instead of just calling:
enemyState = state;

#

you woul do:

ChangeState(state);```
#

in ChangeState you might have a switch:

void ChangeState(STATE newState) {
  enemyState = newState;
  switch(newState) {
    case STATE.Dashing:
      StartCoroutine(waitToChangeState(3f, State.Aiming));
      break;
    case STATE.Aiming:
      StartCoroutine(waitToChangeState(3f, State.Dashing));
      break;
  }
}```
#

something like this

#

you can put whatever behavior you need in this switch, to handle what needs to happen when you first enter any given state

#

Simple example here for having them sort of "pingpong" with each other^

#

but still extensible for other states

grand snow
#

perhaps the switch() is confusing for such an example

slow blaze
#

So where would the function call be?
If I call it within the functions Aiming() and Dashing() wouldn't it still create a Coroutine every time?
If I call it in Start how can I call it again?

wintry quarry
wintry quarry
#

If I call it in Start how can I call it again?
There's nothing that prevents you from calling it in multiple places

#

The only place you're currently changing the state is here:

    IEnumerator waitToChangeState(float delay, STATE state)
    {
        yield return new WaitForSeconds(delay);
        enemyState = state;
    }```
#

so that's the only place you would put the call to the ChangeState function to replace what you have now

#

However you also need to put it in Start

#

to kick things off

slow blaze
#

Oh yeah I get it now thanks
it's going to recursive call through the Coroutine of waitToChangeState

wintry quarry
#

yes

slow blaze
#

yeah thats a lot better thanks for helping

round mirage
#

Hello again 🥲 i always get this error when i try to do the function addItem() i am trying to fix the bug but i dont find where is the problem.public void AddItem(int itemID, int amountToAdd) { slotVerified = 0; for (int i = 0; i < slot.Length; i++) { if (slotTakenID[0] != itemID) { slotVerified += amountToAdd; } else { avalaibleSlot = i; } } if (slotVerified != slot.Length && item[avalaibleSlot].stackable == true) { scriptSlot[avalaibleSlot].numb++; } else if (slotVerified == slot.Length) { for (int j = 0; j < slot.Length; j++) { if (slotTaken[j] == false) { slotTaken[j] = true; slotTakenID[j] = itemID; scriptSlot[j].numb += amountToAdd; scriptSlot[j].Name = item[itemID].Name; scriptSlot[j].sprite = item[itemID].sprite; scriptSlot[j].taken = true; scriptSlot[j].ReloadSlot(); break; } } } } if (Input.GetKeyDown(KeyCode.E)) { inv.AddItem(0, 1); } if (Input.GetKeyDown(KeyCode.A)) { inv.AddItem(1, 1); } if (Input.GetKeyDown(KeyCode.F)) { inv.AddItem(2,1); }

low copper
#

Based on my reading I thought I didn't need to have a yield return line in my SceneRedirect method. However I am getting compiling errors "not all code paths return a value". Any thoughts?

using UnityEngine;
using UnityEngine.SceneManagement;
using System.Threading.Tasks;
using System.Collections;
using System;

public class InitScript : MonoBehaviour
{
    public GameObject logo;
    private Renderer logoRenderer;
    public float AnimationSpeed = .25f;

    private void Awake()
    {
        logoRenderer = logo.GetComponent<Renderer>();
    }

    void Start()
    {
        StartCoroutine(AnimationSequence());
    }
    private IEnumerator AnimationSequence()
    {
        yield return StartCoroutine(AnimationLogo());
        yield return StartCoroutine(SceneRedirect());
    }

    private IEnumerator AnimationLogo()
    {
        float dissolveCurrent = 0.8f;
        while (dissolveCurrent >= 0)
        {
            dissolveCurrent -= AnimationSpeed;
            logoRenderer.material.SetFloat("Stage", dissolveCurrent);
            yield return null;
        }
    }
    private IEnumerator SceneRedirect()
    {
        //SceneManager.LoadScene("Scenes/Intro/Loading/Loading");  
        Debug.Log(AnimationSpeed);
        // yield break; comment out causes error
    }
}
wintry quarry
low copper
#

ah ok. Just just call SceneRedirect at the end of AnimationSequence. That makes sense. I knew something was up.

wintry quarry
#

yeah just make the return type void

low copper
#

thanks. I appreciate it.

polar acorn
round mirage
polar acorn
round mirage
#

oh

#

ok thank you 🙂

round mirage
polar acorn
#

What do you mean "set it at -1"? It appears to be a list of some kind

#

you can't set a collection to -1

round mirage
polar acorn
#

A bag of potato chips is not made of potato

#

Your array is null

round mirage
#

oh

#

so what can i do to fix this ?

polar acorn
#

Don't try to use null as if it were an array

#

Where do you assign a value to slotTakenID?

silk night
#

you have to initialize your array

round mirage
#
    public GameObject[] slot;
    private int[] slotTakenID;
    private bool[] slotTaken;
    private int slotVerified;
    private int avalaibleSlot;
    private slotScript[] scriptSlot;
    void Awake()
    {
        int[] slotTakenID = new int[slot.Length];
        bool[] slotTaken = new bool[slot.Length];
        slotScript[] scriptSlot = new slotScript[slot.Length];
        for (int i = 0; i < slot.Length; i++)
        {
            scriptSlot[i] = slot[i].GetComponent<slotScript>();
            slotTakenID[i] = -1;
        }
    }

    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
    public void AddItem(int itemID, int amountToAdd)
    {
        slotVerified = 0;
        for (int i = 0; i < slot.Length; i++)
        {
            if (slotTakenID[i] != itemID)
            {
                slotVerified += amountToAdd;
            }
            else
            {
                avalaibleSlot = i;
            }
        }
        if (slotVerified != slot.Length && item[avalaibleSlot].stackable == true)
        {
            scriptSlot[avalaibleSlot].numb++;
        }
        else if (slotVerified == slot.Length)
        {
            for (int j = 0; j < slot.Length; j++)
            {
                if (slotTaken[j] == false)
                {
                    slotTaken[j] = true;
                    slotTakenID[j] = itemID;
                    scriptSlot[j].numb += amountToAdd;
                    scriptSlot[j].Name = item[itemID].Name;
                    scriptSlot[j].sprite = item[itemID].sprite;
                    scriptSlot[j].taken = true;
                    scriptSlot[j].ReloadSlot();
                    break;
                }
            }
        }
    }```
#

my array get his value only at the end of additem()

polar acorn
#

You probably want to use the one you've defined as a private variable instead

silk night
#

as a sidenote, have you done !ide ?
It should warn you about overriding properties

eternal falconBOT
round mirage
#

oh you mean i only created the array for awake() but dont exist for addItem() ?

silk night
#

in awake your are using a local variable instead of your property

round mirage
#

oh

#
        bool[] slotTaken = new bool[slot.Length];```
i did this to set the size of my array but i suppose this is this who make this bug ?
raven wolf
#

CHAT GPT wtf i wonder if this works im not a programmer so I have no clue if this code is viable or not like damn im hapy for you chat gpt

polar acorn
#

You need to use the one you already have

#

When you do [type] [name] = [value] that creates a new variable

#

If you want to assign a value to an existing variable, it's just [name] = [value]

raven wolf
polar acorn
raven wolf
rich adder
#

why not just learn how to do it properly ? so you know what the code is actually doing incase it most definitely will break

round mirage
#
        slotTaken = new bool[slot.Length];
        scriptSlot = new slotScript[slot.Length];``` ?
raven wolf
#

i only play guitar 😭

round mirage
plush geyser
#

Over the past few weeks, I’ve been developing an XR Grab Interactable system for my VR guns. My goal is to make it so that if the player grabs near the trigger, the gun will use a preset attach point rather than dynamic attachment, while still allowing the rest of the gun to use dynamic attachment. I’ve tried a few approaches, but so far none have worked as intended. I’m now looking for advice on the best way to achieve this.

mystic flume
#

What does the new unity input system do and how do you even use it

cerulean bear
#

I'm getting an error on line 9

using UnityEngine;

public class SetupManager : MonoBehaviour
{
    [SerializeField] private GameObject[] playerItems;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        for (int i = 0; i < GameData.players.Count; i++)
        {
            playerItems[i].SetActive(true);
            /*PlayerSetupDataMono playerSetup = playerItems[i].GetComponent<PlayerSetupDataMono>();
            if (playerSetup != null)
            {
                playerSetup.playerNumber = i + 1;
            }*/
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

screenshot attached

#

oh yeah heres the error ```NullReferenceException: Object reference not set to an instance of an object
SetupManager.Start () (at Assets/Scripts/SetupManager.cs:9)

wintry quarry
#

make sure it's assigned before you try to use it

cerulean bear
#

ohhhh ok alr

cerulean bear
#

alr thx it works now

bleak glacier
#

So I'm being really stupid: I'm struggling with references. I was using static variables, and I realize that was stupid. I'm trying to backtrack.
levelDropCTRL = GameObject.FindGameObjectWithTag("LVL").GetComponent<LevelDropCTRL>();

I'm not sure how to make normal, non-static variables accessible like I did when they were static.

#

I was able to do stuff like this:

anotherconMod = AbilityScores.conMod;

grand snow
#

you talking about public fields/properties?

#

using the class name is only possible for static members

#

otherwise its used on a class instance

bleak glacier
spring otter
#

Then you'll have access to public variables inside that instance

grand snow
bleak glacier
grand snow
#

Some things can be static but depends on the field/method

spring otter
#

Static variables are a singular instance in the software IIRC

grand snow
#

good lord no that wont

spring otter
#

lol really? am I forgeting something?

grand snow
#

many things 😆

bleak glacier
spring otter
#

Well I tend to GetComponents only on self of set them through the inspector

bleak glacier
#

It was so much easier when I could just reference the tagged object, and pull variables from every script on that object

spring otter
#

Ah right I forgot to set a value for int lmao

grand snow
#
public class Player : MonoBehaviour
{
  public static Player Instance;

  void Awake()
  {  
    Instance = this;
  }
}

Singleton pattern

spring otter
grand snow
#

a static field to let us access a player instance

spring otter
#

If you do you can access public variables from that component by calling the reference name

grand snow
bleak glacier
spring otter
# bleak glacier Yeah I guess I could do that
public class Player
{
  public int health = 0;
  private int maxHealth = 10;
}

public class SomethingElse : MonoBehaviour
{
  public Player onePlayer;

  void Start()
  {
    onePlayer = FindAnyObjectByType<Player>(); 
    onePlayer.health += 1;
  }
}
#

Try this, I think it should work now

#

Btw the "FindStuff" in Unity is not a very good way of doing stuff, it should only be used in small projects/quick prototyping

#

In that example maxHealth wont be accessible because it's private, obviously

grand snow
#

pretty sure you can only Find() unity objects

rough granite
spring otter
#

FindAnyObjectByType<Instantiator>()
I'm using this right now in my prototype and it's working

grand snow
#

yea its a monobehaviour i bet

spring otter
#

Yes

grand snow
#

have a good read what Player is 🤔

spring otter
#

Ah right

#

Missed that, but his player is most likely a MonoBheaviour

grand snow
#

anyway this doesnt help with what they should actually learn

#

Ideally c# is understood well outside of the context of unity

spring otter
#

Well, he seems to be interested in using Unity, not plain C#

spring otter
bleak glacier
grand snow
#

yeesh

#

!learn is the way

eternal falconBOT
#

:teacher: Unity Learn ↗

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

spring otter
raven pilot
#

you can always use unity without c# once you're familar with unity itself and you need to use c# learn it then

grand snow
#

Learning about c# lang concepts is always helpful. the microsoft docs are helpful and detailed

raven pilot
#

idk programming at all, but I'm wanting to learn. so starting with unity without it is more easier to not be overwhelmed. there's multiple ways to do things in unity without the use of c#, learn it step by step, you're just now learning you're suppose to make mistakes and not understand certain things.

grand snow
#

You can get buy but there will come a point where the lack of understanding of OO programming will fuck you over
I was lucky I already knew java and c#

#

Knowing that components are instances and how GC works helps with many things down the line

raven pilot
#

gotta start somewhere 🤷🏽

spring otter
#

Wait you can say swear words here? Nice

bleak glacier
#

There was a time where I knew how to do that. A few summers off and it all goes away.

grand snow
#

its like going to unreal and expecting to learn c++ (you wont)

raven pilot
#

I mean truly idk unity at all, either I'm a beginner in all of this stuff so my question is How much can you get away with visual scripting vs c# anyways?

bleak glacier
grand snow
#

ah yes the old int/int problem

#

doing 4f would ensure it does float/float

bleak glacier
#

Correct

#

Why is that even useful?

#

It seems useless.

spring otter
grand snow
#

Its how it works, 4 is an int literal but 4u is an uint literal ect

rough granite
bleak glacier
grand snow
#

there are ways to define a literal of other types!
🙏 plz do not ask AI

rough granite
bleak glacier
spring otter
#

It's useful sometimes

grand snow
#

for a beginner to learn, id say no
for someone with knowledge already, yes (as you can better tell when it makes up shit)

bleak glacier
rough granite
spring otter
#

Btw I'm not saying for people to blindly throw code at an AI and ask what's wrong, you can past small snipets of code, but it's better for you to analyze your problems and actually ask the AI for advice, if it doesn't work it won't work, then you can seek help with others

bleak glacier
rough granite
spring otter
#

You need to know HOW to prompt the AI too

rough granite
raven pilot
spring otter
#

I'm talking about using AI to help solve problems
Also AI is almost a Google on steroids, you can also find stuff that you saw once in your life by telling it some vague descriptions and it can find it, pretty impressive

raven pilot
#

at this point, kinda wish ai was never created and people just learned how to google shit and use stackoverflow or seek others for help but we're getting off topic of the channel, but that's my 2 cents.

i admit, I'm guilty of using it but I've disciplined myself not to rely on it and do my own research overall

grand snow
#

I always go to docs first when looking up something for a language or lib
I ask AI as a last resort but the vague shit I ask about often gives a made up answer so 🤷‍♂️

raven pilot
#

Now if we get started talking about integrating MCPs with it that might be a whole different conversation

red igloo
#

When using lerp is using the animation curve better to go about doing this than using time.deltatime?

cosmic dagger
#

that's the only way I use lerp . . .

red igloo
bleak glacier
odd grotto
#

😭

bleak glacier
#

Dude I'm going insane

#

I have all but one reference working

#

And there are no compiling errors, and I can't see anything wrong with the code

#

Ah my dumbass forgot to put in the renamed gameobject to the button controller. :}

cosmic dagger
bleak glacier
strong bane
#

Hello, I have a question about cooldowns
Would this be "safe" from frame hitches ? I dont want to have longer attack intervals then what is set
```c#
public void AttackFromTransform(Transform ownerTransform)
{
if (weaponType?.attackProfile == null) return;

    cooldown -= Time.deltaTime;
    
    if (cooldown > 0f) return;
    
    Debug.Log(cooldown);

    weaponType.attackProfile.Attack(ownerTransform, firePoint, this);
    cooldown = parameters.attackInterval;
}```
ivory bobcat
strong bane
ivory bobcat
#

Current, if a minute or two passed because of the game freezing you'll only get one attack and your attack cooldown will be set back to your interval value

strong bane
#

ah okay so ill just accumulate the time and not reset completely to fix?

ivory bobcat
strong bane
strong bane
kindred path
#

So I have code thats supposed to prevent you from not being able to reach the red square, but for some reason my rooms overlap with themselves, if you think you might be able to help me tell me and I'll DM you the code

sour fulcrum
#

No dms

kindred path
#

I’m just desperate cause I’ve been trying for 7 hours today to fix it

eternal needle
# strong bane Hello, I have a question about cooldowns Would this be "safe" from frame hitche...

is weaponType a unity object? if so you shouldnt use ?. on it
usually you would just do as dalphat said and use cooldown += parameters.attackInterval so you are still keeping those extra extremely small values like if cooldown is currently -0.05
so you worry less, there is a max delta time anyways which defaults to 0.3 seconds. if your game freezes for 1-2 seconds, deltaTime will still be 0.3. i wouldnt worry about designing around massive hitches because you shouldnt have massive hitches in the first place. there would 100% be other bugs out of your control if the game could progress seconds at a time

rugged beacon
#

im just checking out r3 and i have no idea whats a reactive value is, anyone got basic an example or something for this in unity ?

strong bane
eternal needle
strong bane
rough granite
kindred path
#

Broken random dungeon generation

hot wadi
#

Does anyone know any way for object to do certain tasks even if they start and stay inactive?

sour fulcrum
#

yeah sure

#

what makes you think you can't

#

this is not code

cosmic dagger
hot wadi
#

Because getting references from a bunch of them is requiring me to fetch each object at a time in a loop, causing a delay at scene loaded

naive pawn
#

perhaps don't use Find or whatever then, use serialized references if possible, or if they're created at runtime, get whatever is spawning them to keep their references

worn bay
#

Hi, how do I make the the gameobjects projected from the camera to game view, to be also projected to the canvas in scene view?

rough sluice
#

Do someone know that why Free Look is working fine for Up and Down but not for Left and Right?:

private void Awake()
{
    //Cursor.lockState = CursorLockMode.Locked;
    //Cursor.visible = false;

    player = GetComponent<Rigidbody>();
    mobileInputs = new PlayerMobileControlsInputs();
    mobileInputs.Player.Enable();

    // Look input binding
    mobileInputs.Player.Look.performed += ctx => lookInput = ctx.ReadValue<Vector2>();
    mobileInputs.Player.Look.canceled += ctx => lookInput = Vector2.zero;

    // Free Look input binding
    mobileInputs.Player.FreeLook.performed += ctx => isFreeLooking = ctx.ReadValueAsButton();
    mobileInputs.Player.FreeLook.canceled += ctx => isFreeLooking = false;
}

private void Update()
{
    // Camera rotation (Y for player, X for up/down)
    float mouseX = lookInput.x * lookSensitivity;
    float mouseY = lookInput.y * lookSensitivity;

    rotationX -= mouseY;
    rotationX = Mathf.Clamp(rotationX, -80f, 80f); // prevent flipping

    cameraHolder.localRotation = Quaternion.Euler(rotationX, 0f, 0f);
    if(isFreeLooking)
    {
        // Free Look to rotate cameraHolder only
        cameraHolder.Rotate(Vector3.up * mouseX);
        //cameraHolder.Rotate(Vector3.left * mouseY);
    }
    else
    {
        // Normal Look to rotate player
        transform.Rotate(Vector3.up * mouseX);
    }
}

private void FixedUpdate()
{
    Vector2 moveInputs = mobileInputs.Player.Move.ReadValue<Vector2>();
    float speed = 2.0f;

    // Move in direction relative to camera's forward/right
    Vector3 moveDirection = cameraHolder.forward * moveInputs.y + cameraHolder.right * moveInputs.x;
    moveDirection.y = 0f;

    player.linearVelocity = new Vector3(moveDirection.x * speed, player.linearVelocity.y, moveDirection.z * speed);
}
worn bay
radiant jewel
#

Hey all. I ran into one of those unused variable warnings on a catch exception (DOTS/ECS workflow with burst). Made no sense to me since debug is using it. My brain sometimes does this thing where it screams at me... it's my intuition. Something creeps up from the depths of my memory and, usually, triggers an out of the box answer... This time it was, "discard your hand, ex, and draw another." Now, that is not exactly what is going on here... but I think you will get the picture as this is how I handled it:

            catch (Exception ex)
            {
#if !BURST_COMPILE
                Debug.LogError($"GPU heightmap generation failed: {ex.Message}");
                _ = ex; // Prevent unused variable warning
#endif
                _ = ex; // Prevent unused variable warning
                return null;
            }

The first discard silences the debug variable warning and the second silences the Burst warning.

grand snow
#

The real solution would be to do catch(Exception) for burst.

radiant jewel
# grand snow The real solution would be to do ``catch(Exception)`` for burst.

My understanding is that catch exceptions cannot be used inside of a burst block and that is why I used the #if !BURST_COMPILE but this works as well because it's not utilizing Burst in the method so it is safe. But I still discard after to silence the IDE.

// Managed method: safe to use exceptions. No BURST guards needed here.
private RenderTexture GenerateHeightmapGPU(TerrainGenerationData terrainData)
{
    //...previous code

    catch (Exception ex)
    {
        Debug.LogError($"GPU heightmap generation failed: {ex.Message}");
        _ = ex; // LDL: Discard(ex) glyph to appease analyzers
        return null;
    }
}
grand snow
#

My suggestion is to have 2 catch blocks, one for burst and one not to solve the issue without using discard

radiant jewel
grand snow
#

your ide has no idea what burst is and id expect an error to be printed in unity if its not fully compatible with burst

#

No idea if exceptions even exist in burst code

#
#if BURST_COMPILE
catch(Exception)
{
    return null;
}
#else
catch(Exception e)
{
    
}
#endif

does this work?

fallen cosmos
#

Does anybody know is it possible to implement asset picking from asset bundles by implementing a custom SearchProvider?

#

I want to make an SDK that ships a Unity project in which you work with original assets packed in a form of asset bundles, but at the same time I need to somehow support native workflow of using these assets in a project as if they were in your AssetDatabase

#

The only thing that I could find in regards to this is to create a custom SearchProvider, which is supposed to be what I am looking for but I feel like there is some caveat that I am not seeing

radiant jewel
# grand snow ```cs #if BURST_COMPILE catch(Exception) { return null; } #else catch(Except...

It took a bit of work, as it was being incredibly picky. This version of yours works without IDE warnings or errors.

#if BURST_COMPILE
    catch (Exception)
    {
        // Burst jobs can’t throw – bail to safe default
        return null; // must match RenderTexture return type
    }
    #else
    catch (Exception ex)
    {
        Debug.LogError($"GPU heightmap generation failed: {ex.Message}");
        _ = ex; // LDL discard glyph
        return null;
    }
#endif
#

If I do not discard I get the error. Every time. Whether a catch block or burst or not.

grand snow
#

well we can clearly see that ex is used so that doesn't make sense

radiant jewel
balmy vortex
#

kk thanks

#

cuz like rn I need to change the actual direction of every input since the camera rotates

grand snow
#

a common way is to change the rigidbody velocity to move or using AddForce()

naive pawn
#

just as a general tip

rough sluice
#

Currently my character uses W, A, S, D keys to move and I have created 4 UI buttons with on-screen button component with binding W, A, S, D for moving chacater to let mobile players move character but now what should I do to use on-screen stick component button for player movement instead of 4 UI buttons for player movement?

balmy vortex
#
if (moveRightAction != null && moveRightAction.IsPressed())
        {
            Debug.Log("hey lets move right");
            var rotation = Quaternion.Euler(0, _camera.rotation.eulerAngles.y, 0);
            var direction = Vector3.right * speed * Time.deltaTime;
            var rotatedDirection = rotation * direction;

            rb = GetComponent<Rigidbody>();
            //transform.Translate(rotatedDirection);
            rb.linearVelocity = rotatedDirection;

        }
``` ^^ what I'm using rn
#

it's still "moving" but it's like barely even noticable

#

@naive pawn @queen adder

keen dew
#

Don't multiply velocity by deltatime. If it's still slow after removing that, increase the speed value

balmy vortex
#

kk

grand snow
grand snow
#

why is this done again and again?
rb = GetComponent<Rigidbody>();

#

modifying velocity will break jumping because if we override y vel to be 0 the rb will no longer fall

#

you can instead get current velocity, modify x,z only and re assign

balmy vortex
keen dew
#

The simplest way in that code is rotatedDirection.y = rb.linearVelocity.y; before assigning

balmy vortex
frozen nimbus
#

I used to many AI to help me code, I feel like a fake dev these days

balmy vortex
#

not sure

rough granite
balmy vortex
vital helm
rough granite
balmy vortex
#

or like wdym

vital helm
vital helm
#

you can tweak stuff from there

grand snow
#

the player having high friction helps it not slide when not moving but ofc will require more speed to move

#

also its often a good idea to greatly reduce how much input changes velocity when not grounded

balmy vortex
grand snow
#

I don't see what you mean in the video gimme a sec

#

Hangon a sec what is this bizarre input

#

It should be a vector 2

#

Wasd going into a single vec2 (with a normalizer too)

balmy vortex
tidal tide
# balmy vortex idk why but changing this also nuked diagonal movement ^^

Just curious how come you've decided to put each input direction into it's own input action, there's nothing wrong with it but it seems a bit inefficient to me, you could bind all movement inputs into one action that way you get all inputs as a single vector2 and you use it as you need or am I wrong here

tidal tide
balmy vortex
balmy vortex
balmy vortex
tidal tide
# balmy vortex maybe but idk how to actually code it in

It's not done in code it's done in your input system action setup where you create the inputs for left right up and down based on wasd, you can have them all in one single action, then that gives you the ability to cast them into a vector2 and you can normalise them easily to fix the diagonal speed issue otherwise you'll have to build a vector2 out of all 4 inputs to normalise them which is messy

round mirage
#

Hello 🙂 someone know why i cant disable my Image component ?? public Image Icon; Icon.enabled = false;

polar acorn
#

What's stopping you?

round mirage
#

me ?

polar acorn
#

Yeah. What's stopping you from doing that?

#

Is there an error? Have you actually tried it and seen if it works?

thorn rune
#

I'm coding an enemy that patrols an area by going between waypoints on a Navmesh. I want the enemy to randomly stop moving, rotate 360 degrees, and then continue - in a scanning motion to try and catch the player. The enemy currently just randomly rotates partially while moving straight forwards, causing it to go off the path and act erratically. What's going wrong?

IEnumerator ScanForPlayer()
{
    // Stops new coroutine starting until this one ends
    isScanning = true;

    // Stops agent from moving
    agent.isStopped = true;
    canMove = false;

    // Set agent velocity to zero
    rb = GetComponent<Rigidbody>();
    rb.velocity = new Vector3(0, 0, 0);
   
    // Failsafe to stop routine after 1000 runs
    int failsafe = 0;

    // Stops rotation once it reaches 360
    while (rotationAngle < 360.5f || failsafe < 1000)
    {
        failsafe++;
        transform.Rotate(Vector3.up * Time.deltaTime * -100);
        if (rb.transform.localRotation.y <= 3.6)
        {
            rb.transform.Rotate(0, 0, 1.0f * Time.deltaTime * 100);                
        }
        else
        {
            failsafe = 100000;
            //canRotate = false;
            yield return new WaitForSeconds(2);

            canMove = true;
            agent.isStopped = false;
            isScanning = false;
        }
    }
}
round mirage
polar acorn
# round mirage

You have a script named Image or you have imported the wrong namespace. The Image class you are using is not the Unity UI one. Hover over the Image type in the variable declaration and see what class that is

round mirage
#

ok

keen dew
#

it should be something like this:

float rotationAngle = 0;

while (rotationAngle < 360)
{
    float rotationAmount = Time.deltaTime * 100;
    rotationAngle += rotationAmount;
    transform.Rotate(Vector3.up * -rotationAmount);
    yield return null;
}

yield return new WaitForSeconds(2);

canMove = true;
agent.isStopped = false;
isScanning = false;
tidal tide
balmy vortex
round mirage
#

oh no i found how to fix it

#

ty 🙂

tidal tide
thorn rune
keen dew
#

How are you starting the coroutine?

thorn rune
#
if (isScanning == false && proxDetect.canBeSeen == true)
{
    int scanChance = Random.Range(0, 10);
    if (scanChance == 1)
    {
        StartCoroutine(ScanForPlayer());
    }
}
#

This runs every Update, so if the coroutine is not running (isScanning is off) and the player is within a certain area, it starts the routine 1/10 times

#

If I coded it correctly

#

Which I'm now doubting... xD

keen dew
#

Yes but if the game runs say at 60 fps then 1/10 times each frame is 6 times per second

thorn rune
#

Oh

dense current
#

Yo i started learning c# yesterday and managed to code a double or nothing cmd game on visual studio i wanna try unity and take a step forward what are some good beginner projects that could help me learn scripting better?

eternal falconBOT
#

:teacher: Unity Learn ↗

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

wintry quarry
#

Or if you want to just dive in and make stuff yourself Flappy Bird is a good one to start with

wintry quarry
#

Looks like you probably have it set up as a Button action

wintry quarry
#

You need to create a new binding and choose "up/left/right/down composite binding" (in older versions maybe also called "Vector2 Composite")

#

then add all those keys to the composite binding

#

(and get rid of the bindings you have now)

balmy vortex
#

ok that works but the debug.log just spits these numbers out that change with inputs but like how do I actually know what key is being pressed here?

limber turtle
#

if i want to increase acceleration but have the same speed, should i just double movement force and drag? i'm trying to make movement during jumps feel smoother in my platformer but i'm not sure how to do it without doing something weird

#

if you jump and then start moving, it feels really slow and annoying to control

#

but giving the player a small movement boost when they start moving just feels weird

#

in the air, i mean

rough granite
#

Or it's failing to update

wintry quarry
limber turtle
#

i'm not sure how to do that in a way that would feel natural

wintry quarry
#

you could also use a higher force for when you start moving than when you are continuously moving

limber turtle
#

i can't clamp because i want to use momentum for some things

balmy vortex
limber turtle
#

that could work

rough granite
limber turtle
#

i could double movement force until you're at half top-speed

#

thank you praetor

wintry quarry
wintry quarry
limber turtle
#

i can't clamp though, i plan on making abilities that will give you momentum instead of fixing your velocity afterwards

#

thank you for the force doubling idea though

#

surprised i didn't think of that myself lol

rough granite
wintry quarry
limber turtle
#

i think i'm alright as of now

#

i just want to use unity's built-in tools for now

limber turtle
wintry quarry
limber turtle
#

so it would be easier to know what you're looking at

balmy vortex
wintry quarry
#

because y is "up", and reight now you're just overwriting the y part with rb.linearVelocity.y

#

e.g.

Vector2 moveInput = move.ReadValue<Vector2>();
Vector3 moveInput3D = new(moveInput.x, 0, moveInput.y);```
opal blade
#

quick question: is there any way to make Rider recognise Unity hlsl symbols like the Light data type? i feel like i might need to add an include path but i'm still not really sure how

brave compass
#

It's possible that you can include the relevant files in here, if those include files have guards to ensure they won't be duplicated.

#

If you're using URP, try adding #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl

opal blade
#

Yes, this was for a custom function

opal blade
primal trench
#

https://pastebin.com/PZJcuia0

I managed to fix the error, but i want to understand it, does anybody have any idea why calling the Handle Input Buffer function in Update would fix the movememnt speed? also is it okay for all this code to be in the player or would i want to seperatr

#

i've seperate non movement things like grappling

#

but all these relate to movement

#

my only theory for why not being able to jump is affecting movement speed is that it's somehow messing up input

#

i guess if i fixed it it doesn't really matter but I want to know why it's happening

acoustic belfry
#

Hi, how i can make my raycast bigger, or autoaim or smt
i mean cuz my shooting feels pretty wacky and i constantly miss the enemy, and i feel like that could go wrong

frail hawk
#

you´d have to use something else than rc

#

Spherecast would be a solution , but could cause other problems

native flame
#

how does using charactercontroller compare to a kinematic rigidbody?

#

for player movement

acoustic belfry
frail hawk
#

not pricesely enough maybe

acoustic belfry
#

pricesely enought?

#

also what is a spherecast?

#

in theory would be a kind of very long capscule?

naive pawn
#

basically yes

acoustic belfry
#

i mean, a capsule that would stretch from point A to hit B

acoustic belfry
#

well, that seems pretty good

#

just a very small spherecast

naive pawn
#

you get a sphere and you send it in a given direction

acoustic belfry
#

haha

acoustic belfry
frail hawk
acoustic belfry
#

i thought i would have to do something complex for fix it

acoustic belfry
#

i mean, as spherecast is like a capsule that stretches, this would jsut be

#

or not? idk im guessing

frail hawk
#

yes

acoustic belfry
#

good

frail hawk
#

you will have to find out which one works better for you

acoustic belfry
#

why make spherecast in the first place?

#

i mean, spherecast makes a list of spheres into the direction

#

capscule cast makes a chonky raycast

#

isn't more usable the chonky raycast?

naive pawn
acoustic belfry
#

ouch

naive pawn
#

depends on how it's oriented relative to the cast direction

acoustic belfry
#

i just want a fat raycast

naive pawn
#

that would be a spherecast

acoustic belfry
#

then a spherecast would be it

#

thanks a lot :3

acoustic belfry
#

can someone explain me why when i fire on this direction, this happens to the cast? (the line is tied to the cast)

rocky canyon
#

maybe its backwards?

acoustic belfry
#

i dont think so, is just when the angle is like this, cuz when the angle is more lowered it shoots forward

frosty hound
#

You need to learn to attempt some debugging before asking questions. A lot of your questions are just "what's wrong?" with a vague image.

acoustic belfry
acoustic belfry
#

here's the code

 {
     Debug.Log("ShootedRifle is even shooting");
     rifle_amount--;

     // Get the mouse position in world space with correct depth
     Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

     RaycastHit hit;
     if (Physics.SphereCast(ray, 3, out hit, Mathf.Infinity, demons))
     {
         Debug.Log("ShootedRifle has Shooted");
         Debug.Log("ShootedRifle hit 3D: " + hit.collider.name);

         EnemyBase enemy = hit.transform.GetComponent<EnemyBase>();
         if (enemy != null)
         {
             Debug.Log("ShootedRifle's enemy isn't null");
             enemy.TakeDamage(5, 1, 3, 3, transform);
         }

         lineRenderer.SetPosition(0, transform.position);
         lineRenderer.SetPosition(1, hit.point);
     }
     else
     {
         // Ray didn't hit — project forward from the camera or weapon
         lineRenderer.SetPosition(0, transform.position);
         lineRenderer.SetPosition(1, transform.position + ray.direction * 100);
     }
 }```
#

weird enought, this issue happens when the spherecast is used

#

why?

bleak glacier
#

So I'm using a save system, and it's working for all of my variables except the ones set by this dropdown menu. The debugs show, and everything else shows, that the variables themselves aren't the problem. The save system just won't save selectedNumber. Clearly there is something here that I don't know.

    {
    // this.levelDrop = data.levelDrop; 
    this.selectedNumber = data.selectedNumber;
    }

    public void SaveData(GameData data) 
    {
    // data.levelDrop = this.levelDrop;
    data.selectedNumber = this.selectedNumber;
    }```
wintry quarry
acoustic belfry
#

the script is in player, wich is related to the camera

wintry quarry
bleak glacier
#

selectedNumber isn't broken though. It just won't save and load.

wintry quarry
#

you said "the debugs show" but which ones? I don't see any in the code you shared

#

Basically you've given us very little to work with here

acoustic belfry
#

the sphere is detecting the floor

#

to wich, if i make it dont do it, the ray works as a charm

#

issue here is

naive pawn
#

layermasks

acoustic belfry
#

yeah

#

the thing is, how i can make a raycast and an sphere cast work together?

bleak glacier
# wintry quarry broken how? What kind of debugging have you done?

I mean, I've debugged selectedNumber, and that's working. The next that displays selected number obviously does that. Saving and loading works in every other script, and I haven't done anything differently. The only different about this script is the dropdown.value.

naive pawn
#

why did you say this then

i dont know how to exactly fix it

acoustic belfry
#

cuz i dont know how to exactly do that

#

thats for why the exactly was for

naive pawn
acoustic belfry
#

huh

naive pawn
#

what are you trying to do

#

what is the purpose of each of those casts

acoustic belfry
#

as shoots, the spherecast must find an enemy at the same time the raycast must find a wall, if any of those both activate, it would count as shoot

bleak glacier
naive pawn
#

so what do you mean by "at the same time"

acoustic belfry
#

when i shot

#

idk, is just, i want it to work as a spherecast for one layer and work as a raycast for another

acoustic belfry
# naive pawn they don't operate over time

holup, what if i do this

{
    Debug.Log("ShootedRifle has Shooted");
    Debug.Log("ShootedRifle hit 3D: " + hit.collider.name);

    EnemyBase enemy = hit.transform.GetComponent<EnemyBase>();
    if (enemy != null)
    {
        Debug.Log("ShootedRifle's enemy isn't null");
        enemy.TakeDamage(5, 1, 3, 3, transform);
    }

    lineRenderer.SetPosition(0, transform.position);
    lineRenderer.SetPosition(1, hit.point);
}```
native flame
acoustic belfry
#

oh no, it fires from the player

#

it decides where to end by the camera

#

or atleasts thats what i feel like it does

wintry quarry
#

well it depends what the ray is exactly doing. It can make sense to do a raycast from the camera to the game world to determine where the player is clicking, but then a separate raycast from the player to the target for the actual shot

native flame
#

fair enough

native flame
acoustic belfry
#

yeah, that seems as the prob, thanks

#

issue now is, how i can make that a spherecast tries to hit the enemy, but doesnt phase away ignoring the ground layer using a raycast?

native flame
#

spherecast only interacts with enemy layer

#

raycast interacts with environment layer

acoustic belfry
#

yes, oh wait

i did it backwards

cuz i did, if sphrecast doesnt hits enemy then check if raycast hits ground. when it should be, if raycast hits ground then check if enemy should be check

#

no wait, that wouldnt work

#

i test it...

bleak glacier
#

@wintry quarry I figured it out. It was my fault.

thick sedge
#

hi

#

Raycasting 1 ray every frame is fine for both mobile performance and pc right?

frail hawk
grand snow
#

Nothing to worry about even in update

keen dew
#

Not even if you do 100 raycasts every update

polar acorn
#

Even if it were a problem for perfomance, FixedUpdate doesn't magically fix that

frail hawk
#

FixedUpdate is not for physics ok

polar acorn
#

FixedUpdate is for things where the second derivative of time is important - the rate of change of the rate of change of time. This is mostly used for physics calculations

frail hawk
#

we are talking about Physics.Raycast right

polar acorn
#

Yes

#

Which is not, in any way, dependent on time

#

And especially not concerned with the rate of change of time

frail hawk
#

if you say the raycast doesnt belong into the FixedUpdate, why is the official documentation using this method then