#๐Ÿ’ปโ”ƒcode-beginner

1 messages ยท Page 118 of 1

queen adder
#

this will add a +0.1 to counters each frame

robust condor
#

Yeah I could add that I guess but this is more of a test

#

What I mean is, I need to run code every frame on the NPC to increment a number

#

So it seems unavoidable to call a function on NPC every frame?

queen adder
#

incrementing a number every frame isn't that costly tbf

#

as long as you dont put some huge blocking logic inside the Update() function you should be fine

ruby python
#

Yeah, just changing a number in update is essentially nothing.

cosmic dagger
ruby python
#

There is also a method to InvokeOnce if I remember correctly. But I've never really used it, just seen it on a few videos in passing.

robust condor
#

Imagine a FSM or behaviour tree and 1000 npcs, do they run all their state machines every frame for every NPC?

queen adder
#

If your npc is not active then the Update function wont run

verbal dome
queen adder
#

also if your Update function has something as little as modifying a state of a counter then its fine tbf

ruby python
#

Anything that is in Update() runs every single frame, even calling other methods/functions etc. So (and please someone correct me if I'm wrong) CoRoutines and the like are more desirable as they take the 'load' off the constant updating.

I'm still learning so I get a lot of things wrong, but I always try and keep my Update()s as empty as possible.

queen adder
ruby python
#

@queen adder I was assuming when active.

queen adder
#

Oh

#

I thought the only time he needs npc's to NOT run update is when its active = false

robust condor
#

Well I think they will always be active because I need to know when NPC has finished sleeping

cosmic dagger
robust condor
#

Unless I make a clock and wake up all the sleeping NPCs with a schedule

ruby python
#

Ah. I understood it as, NPC's are performing tasks throughout the game, when task A is finished, move on to Task B etc. etc.

robust condor
#

Yeah they have a life cycle

queen adder
#

yeah defo sounds like you should use coroutine

#

So after the npc is awake you dont need to run the counter?

ruby python
#

Okay, so sleeping is essentially a Task. So yeah either a timer (like in the video I posted, old, but works), or coroutine.

queen adder
#

esentially be like this:

public IEnumerator WakeNpc() {
    yield return new WaitForSeconds(_secondsUntilNpcIsAwake);
    DoSomethingAfterItsAwake();
}
ruby python
#

!code

eternal falconBOT
cosmic dagger
#

Use a variable as a timer, a timer class, or a coroutine. Those are your options for tracking time and execute a method afterwards . . .

queen adder
#

Idk what timer task you are talking about but whatever you do, do not use a the timer in c#

#

It spawns a new thread

ruby python
#

You could even do something like.

public IEnumerator PerformTask(state Task, float taskDuration) {
    //Change task to the one gotten from above
    yield return new WaitForSeconds(_taskDuration);
    SelectNewTask();
}

Maybe?

queen adder
#

Get mixed up a lot

eternal needle
#

if they're running logic on a ton of AI's, I dont think coroutines like this are a good idea. Itll create a ton of garbage

ruby python
#

Not sure what your Tasks are stored as so edit accordingly.

ivory bobcat
#

The coroutine will nicely handle states and instances for you though, if you opt for the coroutine - has a cost of some memory allocation for managing the state/instance.

cosmic dagger
queen adder
#

So your coroutine wakes up the earliest npc. You'd need the while loop in there too

#

Instead of 1000 coroutines, 1 coroutine checking the min time required to wake the first npc up

eternal needle
#

Not sure what the original problem was tbh

ivory bobcat
#

Cache the yield statements if possible as well unless they're one time use disposables.

queen adder
#

so the logic would call regardless every frame

empty summit
#

was it possible to show a variable in the inspector but not make it editable? just so i can see that it changes

eternal needle
empty summit
queen adder
#

You need to add extra code

ivory bobcat
#

Or assets like Odin inspector read only etc

verbal dome
cosmic dagger
#

Easy to find a ReadOnly attribute online or write your own. Very handy . . .

verbal dome
queen adder
#

why do people do this in unity :[

    [ReadOnly]
    public Vector3 forwardVector = Vector3.forward;
#

I know its longer to add [SerializeField]

#

But its equally as ugly seeing public variables all over the place

#

Even if i needed something to be public i'd do:

[field: SerializeField]
public string A { get; set; }
#

never public string A;

cosmic dagger
#

I didn't know people did that. If given access to other classes, it's preferable to use a property . . .

wintry quarry
verbal dome
#

It's in the naughty example

queen adder
verbal dome
#

Probably just for readability

wintry quarry
#

Oh - probably just to show off the attribute

cosmic quail
#

hey, i wanted to ask how would you handle this issue for a competitive shooting game?
cause torque interpolates right?

cosmic dagger
#

That makes sense. You can't really show how it works if you use a property . . .

queen adder
#

i assume you can do this: [field: ReadOnly]

robust condor
#

Can't use { get; set; } with Odin

queen adder
#

or show their example like such:

[field: SerializeField]
[field: ReadOnly]
private string A { get ; set; }

#

you guys not seen use of public class variables all over in unity?

#

I might be downloading bad packages then

#

๐Ÿ˜ญ

wintry quarry
#

they're all over the docs though

eternal needle
eternal needle
queen adder
#

Sadly bawsi :\

#

People follow these examples and end up writing public all over the house

#

Show people the correct way they'll do it the correct way ;D

cosmic quail
eternal needle
# queen adder I might be downloading bad packages then

Lots of packages or assets can be made by beginners anyways. Like I tried out one AI asset from the "23 for 23" bundle recently and it was absolutely written by a beginner who had a decent amount of time. GetComponent calls everywhere, ton of garbage created

queen adder
#

I only recently realized that we could do [field: Attribute]
Before i was doing:

[SerializeField]
private string _a;

public string A { get => _a; }
ivory bobcat
cosmic quail
eternal needle
cosmic quail
eternal needle
ivory bobcat
cosmic quail
#

but by making a custom character controller yourself you'd have to manually do all the interactions with physics objects, like pushing them and standing on moving objects and such. but with rigidbody it comes out of the box, right?

queen adder
#

john you after a multiplayer physics interaction

#

or single player?

ivory bobcat
queen adder
#

tbf photon quantum has worked pretty nicely for me

#

For the physics stuff

eternal needle
queen adder
#

Backend server side integrates with unity assets

ivory bobcat
#

Like how gravity applies to a rigid body on a slope (sliding) or how fall speed (terminal velocity) isn't game-ish enough

#

It's great for simulating physics behavior with objects though - rolling a ball, firing a cannon, sliding a box and whatnot.

queen adder
#

.e.g. my component can have something like this attached onto it and from my server side code i can get this script and change state of it, it reflects on the client too

#

It just works

ivory bobcat
#

Looks unsafe

queen adder
cosmic quail
queen adder
#

Photon Quantum also has physics support

#

2d and 3d

cosmic quail
# queen adder

wow multiplayer looks complicated. does one have to remake every script from scratch to be able to turn a game multiplayer?

queen adder
#

You dont need to re-write all of it, just the bits where state update is required and the update is on a multiplayer level

#

.e.g. if i was firing a bullet i'd not instniate it using the unity client i'd use photon systems (server sided) and use frame.Create(projectilePrototype)

#

This way all users can see it

cosmic quail
#

interesting

sage mirage
#

Hey, guys! I have a question. How to choose display mode(Windowed, Fullscreen) with a dropdown, I mean how to make the functionality work when someone want to choose in dropdown for example full screen?

#

I have seen videos of how to make full screen to work with a toggle but dont know yet how to make it work with dropdown

queen adder
#

photon quantum is expensive btw well atleast i think

#

0.5$ per ccu

#

I had to write a pre-lobby system so people dont automatically connect to photon lobby

#

It saves $

cosmic quail
cosmic quail
queen adder
#

They are offering the reliable photon cloud

#

No netcode too. So i dont need to worry about shit like endianness

terse raven
#

What is the most efficient way for enemies to detect players in a given range? Because the only option I can think of is if every enemy had a script that constantly measured its distance from the player. But with a lot of enemies this seems a little stupid?

queen adder
#

thank you!

cosmic quail
robust condor
#

@terse ravenCould also run a trigger on the enemies, not sure how performant it is tho

queen adder
robust condor
#

Or overlapshere on the player and see what they can find

queen adder
#

I use OverlapShape with a 2d circle

#

My entities dont use the Y axis ๐Ÿ˜„

robust condor
#

Are there any downsides to pausing using timescale = 0? Last time I did this it paused the entire GUI, but that doesn't seem to happen now. I still need to use GUI, and do script stuff

terse raven
#

I need path finding too because of top down game lol

queen adder
#

๐Ÿ™‚

cosmic quail
#

if its 2d u gotta use something like a-star algorithm right?

queen adder
#

oh 2d i c

cosmic quail
#

not sure if a-star algorithm is the best though

terse raven
queen adder
#

I manage to use navmesh fine with 2 axis's :\

#

But i assume they cant form the navmesh

#

Cause sprites are not models

cosmic quail
queen adder
# terse raven whats this?

You can generate a navigation mesh which tells your game this place is walkable and this place isn't. You can find this in your navigation tab and tag different components as walkable or not.

#

@terse raven you're talking about a 3d game right?

#

Tile clipping in a 2d game will be different

terse raven
queen adder
#

Ok so you dont need a nav mesh

terse raven
#

tile clipping then?

cosmic quail
#

well i think the answer is a-star algorithm but id also want to hear what is said in the ai-navigation channel to be sure

queen adder
#

yeah basically you'd use the A* which denotes a tile like this:

clippingFlags[hash(x,y)] = flag;

where flag can be NORTH_BLOCKED | SOUTH_BLOCKED | EAST_BLOCKED etc.

Each coordinate has a clipping flag where you can block certain directions. From this the A* algo can work out the best route to take to a coordinate

terse raven
#

thanks a bunch!

#

I have asked there just awaiting responses ๐Ÿ™‚

cosmic quail
#

or is rigidbody recommended

#

cause a lot of people recommended rigidbody so idk

sullen zealot
#

hello!
i have a gameobject that has 2 child trigger colliders. is there a way to check onTriggerEnter/Stay/Exit which child got triggered from the parent script?

#

or at least make it so that the parent ignores the second trigger's collisions

#

but keep it as its child

summer stump
sullen zealot
#

what do you mean bubble it?

summer stump
#

Bubble up just means lower tier (child) entities tell the entity above them, which tell the entity above THEM, and so on.

dim yew
#
void RemovePreviousRoom(int index)
    {
        moveable.RemoveAt(index);
    }```
i'm trying to remove an element from a list and i get this error. is there an easy fix for this?
slender nymph
#

your list is null

dim yew
#

sorry, i'm not sure what that means

rich adder
rich adder
#

and you cannot access something that doesn't exist

summer stump
dim yew
summer stump
rich adder
dim yew
#

wait i'm really dumb hold on

lavish roost
#

Hello guys, i have a scaling problem i want to be able to move objects from my inventory based on the current mouse position but when i use the Input.mousePosition variable it doesnt actually match with the screenspace even after dividing through the scales of the parent components im not sure what im missing

[SerializeField] private RectTransform rectTransformItem;
[SerializeField] private RectTransform rectTransformUI_Inventory;
[SerializeField] private RectTransform rectTransformCanvas;
[SerializeField] private RectTransform rectTransformItemSlotContainer;
private RectTransform rectTransform;
private bool clickedSlot = true;
private void Awake()
{
    rectTransform = GetComponent<RectTransform>();
}
private void Update()
{
    if (clickedSlot)
    {
        //Debug.Log(UnityEngine.Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, -10)));
        Debug.Log(Input.mousePosition);

        rectTransform.anchoredPosition = Input.mousePosition / rectTransformItemSlotContainer.localScale.x / rectTransformCanvas.localScale.x / rectTransformUI_Inventory.localScale.x / rectTransformItem.localScale.x;
    }
}
dim yew
rich adder
craggy lava
#

Hi i have a problem with my gravity tool because when i use my tool wheel to activate it then my tool does not work and when i activate it in the inspector it works and the tool wheel just activates the script on the player using

toolScripts[index].enabled = true;

and the script gets enabled it just dosnt work like it should and the LightTool works fine using that method of enabling it (no error in console)

dim yew
rich adder
#

toolScripts[index].enabled = true;

rich adder
dim yew
eternal needle
rich adder
#

you have to select one of the errors

dim yew
#

is this correct?

rich adder
#

yes

dim yew
#

bad screenshot oops

rich adder
#

its this moveable.RemoveAt(index - 1);

#

you're removing at index that isn't in the list

dim yew
#

ahhhh

#

i'm fairly new to lists so i can see how i would make that mistake

#

does this mean that i have to change how i get the length of the list?

rich adder
#

its literally guess work from this side at this point..

dim yew
craggy lava
#

I have made a tool system for a game and it works but after it enables the tool script i need to press again and then the tool script works

slender nymph
slender nymph
#

how about literally any context? what is a "tool system" what does it mean to "enable the tool script" what are you "pressing", what does it mean for it to "work", how are you accomplishing any of this. nobody here can read your mind, mate. nor can we see your screen

fervent ridge
#

chill

slender nymph
#

your input is not needed. but if you feel they've provided enough context with that one message, then go ahead and answer their question

craggy lava
# slender nymph how about literally any context? what is a "tool system" what does it mean to "e...

oh yea sure the tool system is where you hold tab and then a radial menu comes up then you press the tool you would like to use like the Gravity Tool then if you press it enables the script On the player and the player has this inspector and a rigid body and collider but when you select a tool you need to press again after the tool is selected (the script is enabled like the gravity tool script) and then the gravity tool script works like you can pickup objects and rotate and place them

slender nymph
#

don't forget to also show your !code

eternal falconBOT
craggy lava
#

Code was here

wild cargo
sullen zealot
#

the start btn ๐Ÿ˜‚

craggy lava
slender nymph
#

where are the methods inside of the ToolWheelButtonController being called?

craggy lava
wild cargo
craggy lava
wild cargo
#

Do you want it to start holding after the tool is activated in the tool manager?

craggy lava
#

You pickup stuff using E but when you have selected a tool you need to press Left mouse button for the tool to work thats my problem because i want the tool to work when you select the tool

slender nymph
#

and what does it mean for a tool "to work"

#

like is it not appearing visually?

craggy lava
wild cargo
wild cargo
#

Wait nvm

slender nymph
#

you should put some logs in those methods on the ToolWheelButtonController to see when those are being called

slender nymph
#

and it is only after that Deselect is called that it starts working?

#

or are you not fully testing it to see the full picture?

craggy lava
slender nymph
#

yeah i have a feeling it's because you are constantly enabling/disabling the component until Deselected() has been called

slender nymph
#

okay after testing it, that is exactly what is causing this

[DefaultExecutionOrder(-100)]
public class TestThing : MonoBehaviour
{
    AnotherTest thing;
    // Start is called before the first frame update
    void Start()
    {
        var go = new GameObject();
    thing = go.AddComponent<AnotherTest>();
    }

    // Update is called once per frame
    void Update()
    {
        thing.enabled = false;
    thing.enabled = true;
    }
}

[DefaultExecutionOrder(100)]
public class AnotherTest : MonoBehaviour
{
    private void OnEnable() => Debug.Log("Thing was enabled");
    private void OnDisable() => Debug.Log("Thing was disabled");
    private void Update() => Debug.Log("Thing updated");
}

not a single "Thing updated" log was printed for the duration of the test

slender nymph
# craggy lava why is that?

instead of calling ActivateTool every single frame until the object has been deselected, only call it when the object is selected

desert plinth
#

Hi there, I got this script, and it is supposed to decrease the enemy's health when colliding with a game Object with the tag "Attack". Yet nothing happens? The tag is the same, and is attached to the attack.

craggy lava
# slender nymph instead of calling ActivateTool *every single frame* until the object has been d...

how would i do that because this script under is the activation thingy

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

public class ToolWheelController : MonoBehaviour
{
    [SerializeField] private Animator animator;
    private PlayerController playerController;
    [SerializeField] private ToolManager toolManager;
    [SerializeField] private Image selectedItem;
    [SerializeField] private Sprite noImage;
    public static int toolIndex;

    void Start()
    {
        playerController = Camera.main.gameObject.GetComponentInParent<PlayerController>();
    }

    void Update()
    {
        if (playerController.toolWheelOpen)
        {
            animator.SetBool("OpenToolWheel", true);
        }
        else
        {
            animator.SetBool("OpenToolWheel", false);
        }

        switch (toolIndex)
        {
            case 0:
                selectedItem.sprite = noImage;
                break;
            case 1:
                toolManager.ActivateTool(0);
                break;
            case 2:
                toolManager.ActivateTool(1);
                break;
            case 3:
                toolManager.ActivateTool(2);
                break;
            case 4:
                toolManager.ActivateTool(3);
                break;
        }
    }


}
craggy lava
craggy lava
slender nymph
slender nymph
slender nymph
#

so it's not that it is wrong, it's just less correct than what they have

slender nymph
craggy lava
craggy lava
slender nymph
#

create a loop like i suggested

#

inside of ActivateTool

desert plinth
#

I have to admit I am a total noob and I'm not understanding anything rn tbh ๐Ÿ’€

slender nymph
#

i provided a link that will walk you through everything you need to check to ensure that OnCollisionEnter is being called. have you gone through that?

desert plinth
#

I am trying

slender nymph
#

okay well keep in mind that nobody here is a mind reader so if you do not understand something you are seeing on that site, then you have to ask about it

wild cargo
wild cargo
#

Alr

craggy lava
# slender nymph inside of ActivateTool

still nope ```cs
public void ActivateTool(int index)
{
for (int i = index; i < toolScripts.Length; i++)
{
DeactivateAllTools();
toolScripts[index].enabled = true;
}
}

slender nymph
#

did you even read the entire message?

wild cargo
#

Hi there, I got this script, and it is

craggy lava
slender nymph
craggy lava
#

NVM

#

ITS WORKING

#
    public void ActivateTool(int index)
    {
        for (int i = 0; i < toolScripts.Length; i++)
        {
            if (i == index)
            {
                toolScripts[i].enabled = true;
            }
            else
            {
                toolScripts[i].enabled = false;
            }
        }
    }
slender nymph
#

i know, because you are no longer disabling the component every frame

#

also you can literally just do toolScripts[i].enabled = i == index;

craggy lava
#

but this is more readable for me

slender nymph
#

you don't need the if/else because i == index evaluates to either true or false already. and you're assigning to something that expects one of those two values

teal solstice
#

g'day guys, I'm super new to coding, what do you think is the best FPS movment I could do, I have tried a lot of tutorials they just have not worked.

slender nymph
#

they just have not worked
do you mean to say that the movement was not satisfying for you? because if you mean that the code you got from the tutorials didn't work then you didn't pay enough attention to whatever tutorials you followed because there's no reason they shouldn't work, unless you're looking at some truly terrible tutorials that nobody else has followed

teal solstice
slender nymph
#

make sure that your !IDE is configured ๐Ÿ‘‡

eternal falconBOT
slender nymph
#

but that will also not make the tutorials just not work, it just won't provide syntax highlighting, error underlines, and autocomplete

teal solstice
#

thank you, also, when I was doing a launcher script, (followed a long tutorial for it) it didn't work because the photon stuff just will not show up while I am coding

#

it gets super annoying because it gives me 11 errors when i finish

slender nymph
#

don't do multiplayer if you don't know what you're doing. you're going to have a bad time

teal solstice
#

It's realy what I wish to do, so I can test it and have fun with friends and all that jazz

slender nymph
#

sure, but learn what you are doing first

#

you're not gonna go race a formula 1 car before you've even learned to drive. so don't do multiplayer before you've learned to make literally anything

teal solstice
#

thanks for the advice

#

I will just try to only movement

#

and try all of that stuff

ruby tide
#

Hi guys very new here. Iโ€™m working on a 3D breakout game called Cubix. I have the paddle and blocks programmed and a score displays. Iโ€™d like to have scores persist. API call to my own website?

#

How is authentication and authorization normally handled in Unity web gl games?

queen adder
#

Hey, is there a way to detect npc movement?

verbal dome
queen adder
#

i have an npc that follows my player, i need to detect when he moves so i can make that when he moves he starts doing his running animation

teal solstice
robust condor
#

How do I create the input settings asset? The xxxx.inputsettings.asset

bleak prism
#

What's the best way to create a canvas and add text to it in script

robust condor
#

@slender nymphOkay I found it, but it still does not find my mouse and keyboard

slender nymph
#

i have no idea what you are referring to with that last part ๐Ÿคทโ€โ™‚๏ธ

crude brook
#

I have a value that gets incremented by Time.deltaTime every frame (in Update()), how can I call a function every time this value is a multiple of 5? In other worlds, how can I call a function every 5 sceonds?

robust condor
slender nymph
robust condor
#

Already did

slender nymph
#

because the alternative would be to FloorToInt the value, % 5 it, check if you've already called the method for this specific multiple of 5 and if not you call the method

verbal dome
crude brook
#

Alright, thanks

verbal dome
#

You can also use a coroutine to do the delay

queen adder
# polar acorn How are you moving it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class gatomilowmovimiento : MonoBehaviour
{
    public float speed;
    private Transform target;

    void Start()
    {
     target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
    }

    void Update()
    {
       transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    }
}
#

im searching in docs for a way to make the npc dont touch the player tho

polar acorn
queen adder
woeful lagoon
#

Can someone help explain the difference between Update() and LateUpdate() and how LateUpdate() works?

ripe shard
woeful lagoon
queen adder
polar acorn
queen adder
#
transform.position = new(target.position.x, transform.position.y, transform.position.z);```
i made it like this, but the npc is sticking to the player and i want it to follow him
upper sphinx
#

@queen adder You might need to add an offset so the NPC is not trying to match the Player X position.

#

@queen adder Or you could do an distance check within the NPC component

frigid sequoia
#

How do you usually work around player getting crushed by platforms and clipping into the ground?

#

Right now and just did a false safe that tps the player up if they get beneath the ground :p

#

Do you prevent the player to ever get beneath the platform? Do you create a collider beneath it that stops the platform movement if the player is in there? Do you just kill it?

#

I am kinda curious what is like the default thing to do here

verbal dome
#

More of a design question.
If you want it to be forgiving, stop/reverse the platform when it hits the player
If you want it to be hardcore, kill the player

#

Checking if an object is "squished" between two objects can be tricky, though

frigid sequoia
#

Seems kinda messy, can't really think of much more to be honest

teal viper
#

Obviously, the raycast would need to ignore the character layer.

#

And it's best to make that check when the platform already collides with the player.

teal solstice
#

Im having a problem with this script for my looking in my FPS game, know how to fix?

slender nymph
eternal falconBOT
teal solstice
#

its giving me an error with my UpdateCursorLock();

slender nymph
#

yes because that's the line you declare the method and it isn't abstract so it needs a body

teal solstice
#

can you explain better for me?

slender nymph
#

what is different about that line compared to any other line you have a method on

frigid sequoia
teal viper
slender nymph
frigid sequoia
teal solstice
#

maybe the update would be before

slender nymph
teal solstice
teal viper
#

Unless you have situations where it can get crushed between the ceiling and the platform too.

teal solstice
#

I dont knw whats wrong

slender nymph
#

look closer

teal viper
frigid sequoia
teal viper
teal solstice
frigid sequoia
#

In Little Big Planet for example you could be crushed from any force in any direction or conbination of forces in different directions if it was enough

frigid sequoia
teal viper
frigid sequoia
teal solstice
teal viper
teal solstice
teal viper
slender nymph
teal solstice
frigid sequoia
#

I think I could send a raycast from the player up to check only for plataforms and down to check for any valid ground and check that they both return a hit that is at least half of player heigh away from the origin, if they aren't, that means they are clipping

slender nymph
teal solstice
#

oops semi

#

the semi thing

teal viper
teal viper
teal viper
steep shoal
#

anyone aloud to ask question in here?

teal viper
#

Not aloud. You can ask quietly though.

steep shoal
#

whats that mean lmao?

teal viper
#

English mf, do you speak it?๐Ÿ˜ฌ

steep shoal
#

yea its my first language you?

frigid sequoia
teal viper
teal viper
#

If you're specifically differentiating between sides, it makes it less generic.

steep shoal
#

yea grammar isn't my stong side but i get the joke

frigid sequoia
teal viper
#

Anyways, you don't need to ask for permission to ask. Just make sure it's the right channel.

teal viper
frigid sequoia
#

I didn't know you could do that

steep shoal
#

I'm pretty sure this is the right place,

teal viper
steep shoal
#

Rigidbody enemyBulletInstance;
enemyBulletInstance = Instantiate(enemyBulletPrefab, enemyFirePosition.position, enemyFirePosition.rotation);
enemyBulletInstance.AddForce(new Vector3(playerPosition.transform.position.x, playerPosition.transform.position.y, -5f));

#

the enemybullet fires from the correct spot but has the wrong trajectory. how would i fix that?

teal solstice
#

man im taking a break

#

been doing this all day

#

since I woke up

frigid sequoia
steep shoal
teal solstice
#

i still don't understand why im so dumb after going over 5 different courses of coding

teal viper
teal solstice
#

cause every dang time people say, "go over basic knowledge of c#" WHEN I HAVE

#

I JUST CANT FIGURE IT OUT

teal viper
#

Then also check if there are already and cashed collisions. And if there are, make the crush check.

teal solstice
#

IM FRIED

teal viper
eternal falconBOT
steep shoal
# teal solstice IM FRIED

im still pretty fresh i just started for the day, i normally feel like that after a long day and trying to fix an issue so your not alone.

teal solstice
#

I have been up since 2Am until now coding, Im not stopping

#

until

slender nymph
frigid sequoia
teal viper
slender nymph
teal viper
teal solstice
#

unity?

#

i made the script

#

now importing?

steep shoal
slender nymph
#

wdym by importing?

teal solstice
slender nymph
#

then take a break. i don't know what you want me to tell you ๐Ÿคทโ€โ™‚๏ธ

teal solstice
#

i've been pushed around all day and my eyes are super bluuryy

#

so yeah now I can

#

taje a vreak

frigid sequoia
# teal viper On collision exit. To cache just means to save/keep track of some data/reference...

But... you would need to take the collisions reference Onstay, not just on enter, since stuff can move around while on contact with you, how do you exactly clear the cache on exit? And how do you exactly do the crush check anyways? Like you go with each collisions 1 by checking if there is any collision on opposite direction with one of them having enough velocity towards the player?

teal viper
teal viper
frigid sequoia
teal viper
#

Well, you'll get there eventually. It would be pretty simple for you at some point.

#

Actually, you're probably confused by dot product? It's not that difficult if you research it. It's just a Vector operation. Very handy too

unkempt blade
#

guys idk where to start with game development, man

#

like I know what I want to make

#

but I just like

#

have no idea how to do it and its at a point where I'm in "uncharted territory" and there arent gonna be any resources for my specific issue

#

if that makes sense

#

actually you know what? Is chatgpt reliable in helping me with game development? Like can it help me make a game for me

#

anyone have any idea about that?

north kiln
#

!learn

eternal falconBOT
#

:teacher: Unity Learn โ†—

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

polar acorn
north kiln
#

anyone have any idea about that?
Yeah, it sucks, and most people here hate seeing any question that's arised from it, answered with it, or related to it

unkempt blade
open moss
#

I have a Bullet class that has a simple OnTriggerEnter callback to destroy the bullet. Sometimes it works, sometimes it doesn't. Not sure why. I am firing the bullet at the same wall, the wall has collider, the bullet has collider and is marked as Kinematic and Is Trigger. Its Collision Detection is set to Continuous Any ideas?

knotty schooner
#

I'm reading up about Scene Management and additive scenes and I want to be able to unload additive scenes that are no longer required.
I'm aware of the function UnloadSceneAsync however it says in the description the following:

Destroys all GameObjects associated with the given Scene and removes the Scene from the SceneManager

Just to clarify about the bold section, does it simply mean that the additive scene is removed from the Main Scene hierarchy?
So in theory, I can load that additive scene in again if I want?

teal viper
#

I'm not sure you can unload an additive scene. It kinda merges with the main scene afaik.

north kiln
#

Sure you can

#

removes the Scene from the SceneManager
It just means you can't find the scene via any of the GetScene functions

#

because it's not loaded any more

knotty schooner
#

cheers!

teal viper
#

Oh really? I always thought that part of unity was a bit underdeveloped, but I guess I didn't get into it enough.

knotty schooner
#

hey, we all learn new things every day

teal viper
#

For sure

shell osprey
north kiln
#

Your bounds includes 0,0,0, are you sure you want that?

shell osprey
#

whats it do?

north kiln
#
Bounds combinedBounds = new Bounds(Vector3.zero, Vector3.zero);
low perch
#

how do I get all tiles on a tile map?

#

in a list

north kiln
verbal dome
pliant mist
#

why is this doing nothing? it doesn't even print i?

north kiln
verbal dome
north kiln
low perch
verbal dome
#

@north kiln Oh it's my dark reader extension causing that lol

shell osprey
low perch
#

set int i = 0

north kiln
low perch
#

for 10 loops

north kiln
#

Type for and autocomplete it to create a for loop

#

instead of manually typing it out like a pleb

#

forr for a reverse for loop

verbal dome
#

@shell osprey I gotta ask, are you using ChatGPT?

shell osprey
#

yeah ๐Ÿ˜ญ

north kiln
#

I personally made a NullableBounds struct for myself because I hated that ๐Ÿ˜„

teal viper
#

You shouldn't be using bounds for that anyway. That wouldn't prevent the objects from spawning in the holes between the meshes.

shell osprey
#

how do i go about fixing it?

teal viper
#

You'll need a different solution. Since you're using chat gpt, try telling it that there is an issue with this approach.

shell osprey
#

it gives me a new script that changes nothin

pliant mist
#

is move towards a lerp or a teleport?

polar acorn
teal viper
pliant mist
shell osprey
summer stump
# pliant mist oh well now I have no questions

It neither lerps two values nor teleports anything. It is CLOSER to lerping plus increment code I guess if you have to pick one. Teleporting isn't anything like it though.

Lerp nor MoveTowards (despite the name) have anything to do with movement by themselves

verbal dome
shell osprey
#

making sure the spheres actually get randomised

#

ill send the script

verbal dome
#

You don't know what lines changed?

#

Seems like you are just blindly copying from ChatGPT and then asking us to fix it

#

Instead of trying to understand what's going on

unreal imp
#

guys im making a weapon recoil but it seems to not work,anyone knows which thing is bad?```
public class WeaponRecoil : MonoBehaviour
{
private Quaternion initialRotation;
private float randomRot;
private void Start()
{
randomRot = Random.Range(initialRotation.x - 1000f, initialRotation.x + 1000f);
initialRotation = transform.rotation;
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
transform.Rotate(randomRot, 0, 0);
StartCoroutine(BackToNormalRotation());
}
}
IEnumerator BackToNormalRotation()
{
while (true)
{
setRotation();
yield return new WaitForSeconds(1);
}
}

void setRotation()
{
    transform.Rotate(initialRotation.eulerAngles);
}

}

north kiln
#

This needs to be mostly re-written, most of it is bad. Follow a tutorial or something

verbal dome
north kiln
summer stump
rapid coral
#

hello can some1 pm me i need help with something

north kiln
rapid coral
#

im having issues with some code from one of the brackeys tutorials and cant seem to get around it

north kiln
#

Describe the issue specifically and post the !code

eternal falconBOT
rapid coral
eternal falconBOT
north kiln
prime horizon
#

Guys. I'm now working with Dialogue System with Ink intergration. Now one component I need to add is voice acting and background music. What should I do now?

rapid coral
#

after ive written it what do i do

summer stump
summer stump
rapid coral
#

ye

summer stump
# rapid coral ye

There will be a save button. Click that. Then copy the url and paste it here

prime horizon
rapid coral
#

like this?

summer stump
#

For bg music, I like to just stick a source on the camera and have that play the sound file

summer stump
rapid coral
#

like add that or change it for one of them?

summer stump
rapid coral
#

okay thanks

prime horizon
eternal falconBOT
prime horizon
low perch
#

Look at large code blocks

prime horizon
prime horizon
dry ore
#

What are the best practices for components of a gameobject? Like should I make a variable for the rigidbody or just call GetComponent every time? Should I make the variable public or private?

low perch
wintry quarry
#

GetCOmponent is NOT very expensive but it's still not something you should do constantly

#

and there's no reason for a field to be public, pretty much ever

#

especially if you're not accessing it from another script

dry ore
#

So you're saying I probably won't need to access it?

pliant mist
#

What type of movement would I use if I want to constantly move a object by a vector

dry ore
#

I guess go private until I need it to be public

pliant mist
#

the vector will be randomly determined at the start of the game

wintry quarry
pliant mist
#

I want the object to be destroyed on collision but that is all

wintry quarry
#

You need to use a rigidbody then

pliant mist
#

ok thanks ๐Ÿ™‚

upbeat stirrup
#

code bit too long hold on

wintry quarry
#

Just set the object's velocity at the start and make sure drag is 0

#

and that's all you need to move it

true pasture
#

I cant get my mouse to interact with UI. I changed the default input actions for UI new input system is that why?

wintry quarry
true pasture
#

oh mb i couldve tjust tested it

#

which i did and yeah thats why

#

okay ill go back to the default one

#

ty

upbeat stirrup
bold acorn
#

where the report system at or like support for help

true pasture
wintry quarry
pliant mist
#

intellisense is beginning to predict my less than family friendly print messages LOL

upbeat stirrup
pliant mist
#
using System.Collections.Generic;
using UnityEngine;
using static UnityEngine.GraphicsBuffer;

public class asteroidScript : MonoBehaviour
{
    private Vector3 direction;
    private int maxSpeed;
    [SerializeField] private Rigidbody rb;
    void Start()
    {
        direction = new Vector3(Random.Range(-maxSpeed, maxSpeed), Random.Range(-maxSpeed, maxSpeed), Random.Range(-maxSpeed, maxSpeed));
    }
    private void FixedUpdate()
    {
        Debug.Log("should be moving");
        rb.velocity = direction;
    }
}
``` it's possible I am being insane but is this going to cause performace issues if ran 200 times?
upbeat stirrup
pliant mist
#

nothing moves and I don't know why

#

message prints tho

slender nymph
#

are your rigidbodies dynamic?

pliant mist
slender nymph
#

you should check if you are not 100% sure

summer stump
pliant mist
#

then yes

wintry quarry
#

you never set it to anything else

#

and it's private

#

so you couldn't have set it to anything else

slender nymph
#

ah yeah, that'll do it lol

pliant mist
#

thanks

true pasture
wintry quarry
upbeat stirrup
pliant mist
#

ok thanks

clear seal
#

can someone tell me why doesunity crash every time i press s

#

here is my script

slender nymph
#

you probably have an infinite loop in your code

clear seal
clear seal
slender nymph
#

yes, that loop can never end. just use an if statement like you're doing below

clear seal
#

oh ok

slender nymph
#

remember, loops run to completion. and since nothing inside of that loop can change the value returned by Input.GetKeyUp(KeyCode.S) then it never exits the loop

clear seal
slender nymph
#

kill it with the task manager

#

also it's not a crash. crash implies it closed

silver wasp
#

hello friends, I have a question, where can I start to look for FPS tutorials?

clear seal
slender nymph
#

inb4 brackeys

clear seal
#

go search fps builder

summer stump
clear seal
silver wasp
slender nymph
#

start with the basics !learn

eternal falconBOT
#

:teacher: Unity Learn โ†—

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

clear seal
#

me

silver wasp
#

lets go, thank you! i'll be back

clear seal
#

boxfriend

summer stump
slender nymph
#

that's not specific

summer stump
clear seal
summer stump
#

GetKeyUp/Down are only true one frame

slender nymph
#

that will rotate by 10 degress on the X axis once you release the S key

#

also keep in mind that for 2d you probably want to be rotating on the Z axis, not the X axis

silver wasp
clear seal
slender nymph
#

it most certainly rotated by 10 degress on the X axis. but like i pointed out, that's probably not the one you want to rotate around ๐Ÿ˜‰

clear seal
#

but how do i repeat it infinitly

summer stump
slender nymph
# clear seal but how do i repeat it infinitly

well GetKeyUp only returns true the first frame you release the key. if you want to check for every frame the key is up use GetKey but just invert the condition (check it is false instead of true)

clear seal
#

um i dont know if you guys knew what i meant but i wanted the circle rotate everytime exept when the S key is pressed

summer stump
summer stump
#

This will rotate constantly EXCEPT when you press s

slender nymph
#

also make sure to multiply your rotation by deltaTime otherwise it will be zoomin

clear seal
#

oh nvm

summer stump
clear seal
#

and so i use coroutine to make it continue

slender nymph
clear seal
slender nymph
#

and?

summer stump
clear seal
slender nymph
#

huh?

summer stump
clear seal
slender nymph
#

no

summer stump
slender nymph
#

just the if statement inside of Update is sufficient

summer stump
#
void Update() 
{
  if (!Input.GetKey(KeyCode.S))
  {
    //rotate
  }
  else 
  {
    // move
  }
}

Could reverse this of course. I just copied from above cause phone coding sucks

clear seal
#

yeah i think i should go to sleep

clear seal
#

pls respond

#

i wanna sleep

slender nymph
#

just go sleep and come back to it with a fresh mind tomorrow. at this point we have to spoon feed you the answers which is something that nobody really wants to do

summer stump
dry ore
#

I'm making a 2d platformer with a gamepad as input, do people usually use analog left and right movement or a couple of different set speeds (run and walk)

real falcon
#

im looking to make a door, and I'm wondering if I should use a rigidbody or what

#

I am not sure what the best way to rotate it would be, ideally it would stop if it hits something for example

#

like I could just change the objects rotation, but would it properly push the player and other objects if I did that?

#

or does it have to be in a specific method? does it have to use a specific method?

eternal needle
# real falcon im looking to make a door, and I'm wondering if I should use a rigidbody or what

Unfortunately itdepends on everything in your world. If your objects move via rigidbody, then yes a door moving via rigidbody should push it. But you have to make sure its rotating with enough force, and not too much to knock some objects out of the world. I found joints pretty useful for this because you can literally make the entire door with no code. It just wont automatically open (or close) depending on how you set the joint constraints. By setting a target rotation, it can automatically try to close at all times for example
If you just directly change the rotation, then it will teleport into objects, and those objects may try to depenetrate themselves (rigidbodies will) but itll be clunky and you may end up on either side of the door by the end.

eternal needle
real falcon
#

I tried to do that but I can only get it to be solid to the player, without the player really pushing it

#

I think it's beacuse the player doesnt have a rigidbody, just a character controller and a collider

#

also when its pushing the player it seems to be "choppy" do you know what that is a result of?

#

idk anything about game physics

eternal needle
#

either you need to add a way for objects to push your character controller in a way that looks like physics, or use a rigidbody instead

#

and yea your player wont push the door because no physics

real falcon
#

hm, well I don't want to use a rigidbody because in my experience you basically just cant have tight controls with a rigidbody

#

you're just at the mercy of chaotic physics simulations

#

how would I make the door stop if it touches the player, without it pushing the player at all or intersecting them

#

I tried OnCollisionEnter but it didn't seem to work

#

wait no

#

let me fix

#

nope still doesn't work

eternal needle
real falcon
#

hm its set to kinematic is that why

eternal needle
#

if you just adjust the transform then you gotta do like an overlap check or something

#

not really sure whats best there

real falcon
#

making it non kinematic makes it stop but it jitters when it touches you, depenetrating again maybe?

#

also, I want to lock the x and z rotation but when I do that it rotates from the center of mass, not the object pivot I set

eternal needle
real falcon
#

the door is just a box collider and a rigidbody, moving with MoveRotation in FixedUpdate

#

im gonna watch a video about game physics tho so I know what the foundation of this is

thin carbon
#

!code

eternal falconBOT
empty yoke
#

is there any good documentation somewhere on good practices for persistent data between scenes? I have two scenes I want to be able to move between, and some core data needs to persist, (meta upgrade data for a roguelike effectively, and then on the opposite scene change, currency data that carries from runs back to the hub world)

I've seen things like PlayerPref data, and something about having a master scene that never disables, but I'm not really sure what like...just a good place to start and better understand would be.

summer stump
#

DontDestroyOnLoad is, itself, a scene that will make it so objects are not destroyed when a new scene loads. So you put an object in that scene when you want it to persist

#

Additive scene loading is very similar, but can do it with prebuilt scenes and it's pretty common to have a scene with UI and manager scripts, then load your location/map/whatever on top

empty yoke
#

Oh I see, so I could put data managers under that DontDestroyOnLoad part, and I'd be able to call that data from any scene, or similarly with a prebuilt scene as y ou described

summer stump
#

Exactly. That way it is all just in memory instead of having to read and write to and from disk

empty yoke
#

It's really that easy huh?

#

Thank you!

tough lagoon
# empty yoke It's really that easy huh?

Yes! Just remember, it'll break any direct references from the inspector. So you'll need to use a singleton pattern, or other method to find it and get the settings when you change levels

#

And be careful not to have more than one

#

Singleton patterns probably the easiest way to access it and avoid that problem

empty yoke
#

already using singleton for all my managers thank god ๐Ÿ™

silent idol
#

I'm wondering what's the best way to save the position of the player gameobject before a scene change, and teleporting them to the same position when the next scene exits?

  1. Player clicks on object that triggers scene change. Save his current pstn.
  2. when the player presses the return key (ESC)/returns to previous scene, load the player position that was saved in 1.
#

I already have a working scene changer, just need to make sure the player position is saved... or alternatively, the player is teleported to the location of the scene changer object itself when he returns to the previous scene.

modest dust
silent idol
woven crater
#

is this a good way to make instance of weapon that im gonna have like 100 of in the future?

wintry quarry
silent idol
woven crater
#

i mean create instance of this Scriptable object

silent idol
#

oh i see

#

so each gun has 3 types?

#

laser, shoot and sniper

#

modes of fire

woven crater
silent idol
#

yeah my english bad

#

but i think that should be fine

woven crater
woven crater
#

stuff like items in binding of isaac that change the game in many aspect like slowdown time. give random enemy debuff and changing player stat

#

does it still work?

silent idol
woven crater
#

the artifact is a seperate thing that player can collect . not apply to weapon

wintry quarry
silent idol
#

OK so whats the point

woven crater
#

using enumerable field?

wintry quarry
#

An enum

silent idol
#

They're not relevant to the gun SO

woven crater
# silent idol but i think that should be fine

ah i see the misundderstanding. i thought you say modifying one thing should be fine using alot of bool method like that. i was asking if it okay to use this method on create an artifact system that change many different thing in the game?

silent idol
#

But seems a Lil clunky

#

Might be better to make an artifact and list what it does

#

In a SO

woven crater
shrewd swift
#

Does the "get gameobject with tag" work with UI elements ? Such as a panel/canvas

wintry quarry
#

Note that Canvas is an actual component and Panel is just a cute name for a GameObject with an Image component on it. Either way they're GameObjects

#

Everything you see in the hierarchy window is a GameObject

woven crater
#

@wintry quarry oh i see

#

another question. should i use switch case to check for what type of shooting or use if statement

rare basin
#

You can use everything you want, even a dictionary

woven crater
#

i watch enough yandere dev documentary to have paranoid on which method i should you

silent idol
#

Switch cases and if statements aren't that far off

#

In performance

#

What really fucked him over was his overuse of the Update method and GetComponent spam

#

Also the fact that mf doesn't seem to know what a script able object is

woven crater
#

oh thank god im paranoid on if i should put stuff in update instead of using event or call from another class

shrewd swift
#

(Yes its visual scripting but here it doesnt matter)

woven crater
silent idol
#

And try to use script able objects where you can

#

Correction, it's FINE to use getcomponent once or twice

woven crater
#

i saving Awake for when i need some script to run before start

silent idol
#

But calling it every frame

#

Is where you run into issues

woven crater
#

so get component in start() is fine?

#

i think this is the wrong place to post this

#

its cool?

#

yea

silent idol
#

but not every frame

#

general rule of thumb, update should only contain methods and code that is fairly lightweight

#

anything that requires lookups should be called selectively or using an event system

woven crater
#

got it. thank much for help ๐Ÿซก

#

is there a more simple way to delay each forloop than using Coroutine?

wintry quarry
#

With a delay inside the loop

#

This is a really weird way to do it, and wasteful too

woven crater
#

blushie typical self_effort

hardy mist
#

For people new to async/await approach,
Let's say we have a method:

public async Task RenameUser(string userId, string newName) { throw new NotRegisteredException(); }

What will the return type look and how can I handle the exception?

modest dust
#

The scene changer itself should have a field for spawn position

silent idol
#

yep

#

so uh, the list/dict inoputs the spawn position var from scene changer right,

eternal needle
modest dust
hardy mist
silent idol
modest dust
silent idol
#

i see

modest dust
#

Could be anything you want, just an example

silent idol
#

okay i get it now, thanks!

eternal needle
#

The doc also has an example with an async task so you can see what goes inside the method

hardy mist
eternal needle
bright zodiac
#

many ways to check if a task was completed or was cancelled. as I've written in other channel, you can do .Result or try-catch it's CancelledOperationException exception

#

you don't want that ContinueWith in Unity when running it via Task.Run just a heads up

#

instead you'd want to make your own dispatcher

hardy mist
# bright zodiac you won't get a clean try-catching in async/await, instead it will be much worse

Don't agree, here is why (but feel free to correct me):

How can I handle an exception outside the coroutine?
How can I preserve the exception stack? (e.g. I did StartCoroutine(_DoStuff(null)), but _DoStuff() isn't supposed to receive null, so it throws NullPointerException().
How would you know who sent null? Coroutines erase the call stack, which is horrible in production, as you can't trace the error source.

safe socket
#

I am using moveposition for movement and using transform.position for keeping player in bounds. It is causing glitches as the player will get stuck in bound position. IS there an easy fix or do I need to change the transform.position to moveposition for keeping player in bounds

wintry quarry
celest holly
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BulletMove : MonoBehaviour
{
    public float bulletSpeed;

    private Vector3 newPos;
    private Vector3 originalPos;
    
    void Update()
    {
        originalPos = new Vector3(transform.position.x, transform.position.y, transform.position.z);
        transform.position += transform.forward * Time.deltaTime * bulletSpeed;
        newPos = new Vector3(transform.position.x, transform.position.y, transform.position.z);
        CheckForCollision();
    }

    void CheckForCollision()
    {
        float distance = (newPos - originalPos).magnitude;

        Ray ray = new Ray(transform.position, -transform.forward);
        RaycastHit hit;

        Physics.Raycast(ray, out hit, distance);

        if(hit.collider != null)
        {
            Debug.Log(hit.collider.gameObject.name);
            Destroy(gameObject);
        }
    }
}

is this the most efficient way of fast bullet travel detection?

wintry quarry
celest holly
#

i heard rigid bodies dont detect collisions if the bullet is too fast though

#

is there any other approach

wintry quarry
celest holly
#

tghank you

wintry quarry
celest holly
#

for some reason i thought the position would update so i tried putting it in a new vector 3

#

can i just do it for both?

wintry quarry
#

Yes you can do it for both, but really it won't be necessary to even have these fields when moving with a Rigidbody

celest holly
#

yeah i deleted them now but i just wanted to know for future reference

#

thanks again

#

ill play around with the rigid body instead

dark sandal
#

pls help me i downloaded unity but it dont downloaded visual studio 2022 if i open an skript i get to visual studio code

teal viper
#

Don't crosspost

pliant mist
#

how do I find the gameobject hosting my script?

languid spire
#

gameObject

pliant mist
#

that doesn't work

#

not even sure what that really mean to be honest

languid spire
#

that is not what I wrote

pliant mist
#

well if thats the case lemme go write what you wrote

languid spire
#

do you not know that C# is case sensitive?

pliant mist
#

works

#

thanks

wintry quarry
languid spire
#

btw you dont even need gameObject in this case. transform.position does the same thing.
Time to go and learn Unity I think

wintry quarry
#

Just transform

warm raptor
#

hello I have this issue in my code : Assets_Script\PlanePhysique.cs(53,22): error CS0266: Cannot implicitly convert type 'double' to 'float'. An explicit conversion exists (are you missing a cast?) but I dont see were there is a "double" in my script

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

public class PlanePhysique : MonoBehaviour
{
    //constante 

    private float g = 9.81f; //pesenteur 

    // constante air

    private float Mair = 0.029f; //Masse molaire air
    private float R = 287.0f; // constante des gaz pour l'air sec en J/kg.K
    private float pAir = 0f; // Masse Volumique de l'air
    private float L = 0.0065f; // gradient de tempรฉrature standard de l'atmosphรจre en K/m 

    //condition de vol

    public float Tempรฉrature = 0f; // tempรฉrature en degrรฉ Celsius 
    private float TempรฉratureKelvin = 0f; //tempรฉrature en Kelvin  
    public float PressionAtmosphรฉriqueNiveauMer = 101325f; //pression atmosphรฉrique en Pa 
    private float DensitรฉAir = 0f;

    //Position avion 

    private float Altitude = 0f; // Altitude de l'avion 

    void Start()
    {
        TempรฉratureKelvin = Tempรฉrature + 273.15f; // calculรฉ la tempรฉrature en Kelvin
        MasseVolumiqueAir();
    }

    void FixedUpdate()
    {
        //rรฉcupรฉrer les valeurs du joystick
        float xAxis = Input.GetAxis("Horizontal"); 
        float yAxis = Input.GetAxis("Vertical");

        Altitude = transform.position.y;
    }

    void MasseVolumiqueAir()
    {
        pAir = PressionAtmosphรฉriqueNiveauMer / (R * TempรฉratureKelvin); // calcule la Masse volumique de l'air
        Debug.Log(pAir);
    }

    void CalculDensitรฉAir()
    {
        DensitรฉAir = pAir * Math.Pow((1f - (L * Altitude) / TempรฉratureKelvin),g/(R*L)); // <-- THE LINE WITH THE PROBLEM 
    }
}

wintry quarry
#

Math.Pow returns a double

warm raptor
pliant mist
#

I'm not sure how to make distance a vector and then use the vector for less if statments but I am sure it's possible

wintry quarry
#

You're accessing it like 20 times

#

Making copies every time

#

Just do it once

pliant mist
#

oh shoot

wintry quarry
#

Also why do separate xyz distances?

pliant mist
#

I'm not sure how I am supposed to only chance the one axis and how to find out if they are greater or less than stuff using a vector3

wintry quarry
#

You could just do something like

asteroid.transform.position = Vector3.MoveTowards(player.transform.position, asteroid.transform.position, maxDistance);```
#

This would replace all of your Update code

pliant mist
#

oh stepping by maxdistance is genius, I don't want the asteroid to move the player tho,

wintry quarry
#

Nothing in there will move the player

#

A secondary issue here is Rigidbody motion isn't going to play too nicely with this Transform motion.

pliant mist
#

let me try this first

wintry quarry
#

Wait is this supposed to wrap around

#

Like asteroids

#

Because my code is just limiting the distance, I think I misinterpreted a little ๐Ÿ˜›

pliant mist
#

yes, it's supposed to wrap around

#

it works now just when rendering like 15 there are some issues

#

30*

wintry quarry
#

Are you sure this code is the issue? Have you profiled it?

If so, then try reducing the number of copies you're making of the positions like I mentioned above.

#

More caching. More local variables.

pliant mist
#

ok, I removed all of the transform and all variables are private, I changed the number from 30 to 15 but the fps is still 5

#

like an unwavering exact 5 it's strange

wintry quarry
#

You need to use the profiler

#

Otherwise how do you know this code is even the issue?

pliant mist
#

yea fair I'll figure that thing out thanks

#

ookay this is gonna be more difficult to understand than I thought

woven crater
#

cursed?

wintry quarry
#

Yes cursed

woven crater
#

how to uncursed?

frigid sequoia
woven crater
#

random point distribution

wintry quarry
woven crater
#

thank. will look into it

waxen aurora
#

Does exist a way to lerp via code the Weight or the Vignette Intensity of a Global Volume?

waxen aurora
#

I wonder if its possible to do it by using Leantween

#

So far I found a way to suddenly do it

#

now I need an interpolation

wintry quarry
#

Interpolation is always the same

waxen aurora
#

true

#

I usually achieve that with Leantween.value since is visually simple and has lots of parameter to play with

#

but for now it doesnt seem working

ionic zephyr
#

why would you use fixed update apart from physics?

wintry quarry
# ionic zephyr why would you use fixed update apart from physics?

For anything that you want to be consistent regardless of framerate. deltaTime can only accurately adjust for framerate discrepancies for constant/linear changes over time. Anything with second order changes over time (acceleration, growth of gaining money/points, ticks in a simulation game) requires a fixed time interval for deterministic simulations.

ionic zephyr
#

and why is fixed update associated with physics?

wintry quarry
#

For exactly the reason i just described

#

To give a consistent, repeatable simulation in the presence of second order changes over time (for example acceleration due to gravity or any other forces)

ionic zephyr
#

second order you mean x^2 for example?

gaunt ice
#

d/dt^2

wintry quarry
#

In this case m/s^2 but sure

neon fractal
wintry quarry
# neon fractal https://streamable.com/u7y2ia knows when the second tab is active, the game free...
ionic zephyr
#

you dont mean to the power of 2, do you?

#

And I dont understand the "tick" system in Unity

#

if anyone could explain

gaunt ice
#

do you know what is differentiation?

ionic zephyr
#

not really

woven crater
#

what is icon type? can i use it to like assign icon to my item?

#

or i just use image type for it

#

or sprite.... idk anymore

queen adder
#

im new and kinda wanna try making something anyone got ideas

eternal falconBOT
#

:teacher: Unity Learn โ†—

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

queen adder
#

also i dont wanna learn mobile and vr

waxen aurora
#

I''m trying this approach, guess I have to interpolate the 3rd parameter, how can do it?

wintry quarry
#

Same way you interpolate anything

#

Use a coroutine, or Update, or a tween library

languid spire
# queen adder no i know how to code ( a lil)

learn is not just about coding although it will teach you how to code with Unity. Nobody forces you to learn mobile or VR although there is very little difference when using Unity

queen adder
#

ok

waxen aurora
#

the thing is, even if tween the T, do I need to call this Interp function everyframe?

wintry quarry
#

The whole point of the tween library is to not have to do anything in Update or a coroutine

#

IDK if leantween has support for custom tweens. DOTween does

woven crater
#

i realized i can just put many scripable class inside on script so i delete all

#

SO script and put it into one SO script

#

now i got this error

wintry quarry
#

Filename has to match class name

#

So one file per class

woven crater
#

ah....

#

thank you

wintry quarry
#

Not sure why you'd want to do that anyway

woven crater
#

look clean

timber tide
#

I'd actually would pack a bunch of SOs together if I could

wintry quarry
woven crater
lost hamlet
#

You actually can do that if you use an assembly, tho that's a huge pain to setup

waxen aurora
#

At the end I achieved the tween with this code, even if I think it can be done in a clear way

woven crater
#

should i use list or enum to hold a list of scriptable object?

lost hamlet
#

Iirc you can also manually add components using AddComponent(typeof(SomeComponent)) but I don't know if that works in editor

lost hamlet
#

Why an enum?

woven crater
#

why not?

timber tide
#

I understand why it doesn't work with the editor, but I could easily see it working with an attribute to define the SO

languid spire
#

how would an Enum hold a List of SO's?

woven crater
#

ah isee

timber tide
#

but until then I'll stick to serialize references

lost hamlet
#

Also I know JsonUtility isn't that great but can it serialize tupples ?

languid spire
#

no

wintry quarry
woven crater
#

also i would like to take a deep appriciation to this chat that help me alot.the big part that i like about this is the rule is not so strict that only question and answer can be send here or by god using "threat" for question.

#

as a person with extreme social anxiety asking for help through a thread feel very isolated

elfin gale
#

(I don't really know if this is the right channel to use :'D)
Hello, I'm really new to coding and overall game making, and i have this reoccurring problem with my game (I'm making Snake for a school project):
Every time that I build my game there is this problem when I move to a second scene (I have main menu and scene for playing) it all turns black, but it only looks like that if I use another computer, on mine it's all fine.
Is this maybe something that other's struggled with/a common problem? I haven't found any information about it online.
All that there is, is just the player, snake's segments, score, sound and pause menu (when u click Escape).
I can add all the information needed!
(I attached the photos for how the game looks like for me, and for another player on another computer).

sullen zealot
#

hello!
i have a gameobject that creates a gameobject but not as a child(and i want to keep it that way).
i want the created gameobject to follow the gameobject that created it. is there a way to reference in script the "creator" gameobject?

sullen zealot
elfin gale
elfin gale
amber spruce
#

how do i instantiate smth between 2 points

#

so it would be a random spot inbetween those points

sullen zealot
#

Random.Range

sullen zealot
# elfin gale

show the scripts associated with the backgroud gameobject

sullen zealot
amber spruce
#

2d

#
        Instantiate(enemyPrefab, new Vector3(Random.Range(spawnPoint1.x, spawnPoint2.x), Random.Range(spawnPoint1.y, spawnPoint2.y), 0), Quaternion.identity);

#

thats what i have so far but it has some errors

#
[SerializeField] private GameObject enemyPrefab;
[SerializeField] private float numberofenemies;
[SerializeField] private Transform spawnPoint1;
[SerializeField] private Transform spawnPoint2;
#

those are my variables

sullen zealot
amber spruce
#

Severity Code Description Project File Line Suppression State
Error CS1061 'Transform' does not contain a definition for 'x' and no accessible extension method 'x' accepting a first argument of type 'Transform' could be found (are you missing a using directive or an assembly reference?) Assembly-CSharp C:\Users\vinny\Shadow Brawl\Assets\Scripts\EnemySpawner2.cs 22 Active

sullen zealot
#

oh

#

use transform.position.x

elfin gale
sullen zealot
#

ex: spawnPoint1.position.x

sullen zealot
#

try making it a prefab

elfin gale
#

I'm sorry I don't really understand what i have to do sadok

sullen zealot
#

What are Prefabs in Unity? In this video you will find out everything you need to know!

More on prefab workflows: https://docs.unity3d.com/Manual/Prefabs.html

Join the community โžก๏ธ https://www.yetilearn.io/

In this tutorial, we'll be showing you how to create and use prefabs in Unity. Prefabs are a powerful feature of Unity that allow you to ...

โ–ถ Play video
#

drag the "background and pause menu" like he does with the cube

#

or just the background photo

#

try and see what works

elfin gale
#

okay Imma try it, thank you

sullen zealot
amber spruce
#
void Update()
{
    for(int i = 0; i < numberofenemies; i++)
    {
        SpawnEnemy();
    }
}

private void SpawnEnemy()
{
    Instantiate(enemyPrefab, new Vector3(Random.Range(spawnPoint1.position.x, spawnPoint2.position.x), Random.Range(spawnPoint1.position.y, spawnPoint2.position.y), 0), Quaternion.identity);
}

so this should work right

rare basin
#

it will spawn numberofenemies every frame

amber spruce
#

oh wait yeah lol

#

but that should spawn numberofenemies

#

i never have been good with for loops

sullen zealot
#

do you want it to spawn them simultaneously?

amber spruce
#

yeah

#

its just so they arent all in the game at once