#💻┃code-beginner

1 messages · Page 344 of 1

slow pecan
#

Alrite, will try them all, and see which I prefer most. ty for helping me out

#

glad to know that I should stop focusing on tags

hasty sleet
#

Tags are good if you're writing code quick and dirty while rapidly prototyping and don't want to write scalable code

#

Whatever a tag can do, a TryGetComponent<UniqueComponent>() can do the same

rich adder
#

also the most important part, strings aren't type-safe, easy to mess up. spelling errors n all

cosmic dagger
#

tfw you don't receive an error for a misspelled tag . . . 😔

rich adder
#

compiler: "its all valid!"

slow pecan
#

ive had that happen a few times lol. Also found out that I need shutoffs for in case the player becomes null

cosmic dagger
#

null check . . .

rich adder
#

ohhh

cosmic dagger
#

had to think about it myself . . .

#

guard clause for the actual terminology, no?

slow pecan
#

ok thx

#

i didnt know there was specific terminology for it mb

topaz mortar
#

I have an inventory with itemslots and then items that go in that inventory
How would I save this to Cloud Save (json format)
Do I just put itemslot on each item, then if I get a new item I have to check all the items to see which itemslots are available
Or do I keep a separate json file that tracks which item ID is in which itemslot?
Or some other option?

cosmic dagger
#

save the item id and its quantity . . .

topaz mortar
#

there's no quantity and the items are saved on Cloud Save in json, not in unity

rich adder
#

json is json, doesn't matter where it saved

wintry quarry
#

Presumably something like

{
  "SlotNumber": 6,
  "Item" : "Fork"
}```
topaz mortar
#

the thing is, players can drag items, so slot 19 could be empty while 1-18 is filled and 20-50 is filled
if I just save them in one big json, then my server needs to check all those items to find an empty slot

wintry quarry
#

Simply don't have an entry for empty slots

#

Json is just a serialized data format

#

You don't do code logic on JSON itself

topaz mortar
wintry quarry
#

Why can't it just be part of the overall save file

slate haven
topaz mortar
#

because there will be 100 items in that json file and I don't want to loop through all of them to find an empty slot?

wintry quarry
#

Also you're talking about servers, and that's an incredibly vague term that means very little to us. Is this a networked game?

wintry quarry
cosmic dagger
#

nada, zip, zilch, none, nothing, not-a-problem . . .

topaz mortar
#

so there's no need for a secondary file like inventory to track which slots are available?

#

remember this is on my server, not client

#

it might have to do it for hundreds of players at the same time

rich adder
#

a very complex json can be literally a few megs or less, you shoud be fine

wintry quarry
#

You have to realize we have no context about your game or your system

topaz mortar
#

every time an item drops

hasty sleet
#

Is someone trying to prematurely optimize

wintry quarry
hasty sleet
topaz mortar
#

it's just the format I'm saving the items in

wintry quarry
#

Don't mix up cold storage with runtime memory structures, they needn't be the same

slate haven
hasty sleet
#

If you have an item selected in Scene view while hitting play then the performance drops, in my experience, and I get at least 4x improved performance while just running in build mode

topaz mortar
#

the serve rwould have to load the json from Cloud Save every time
then convert it to items, then loop through all the items

wintry quarry
wintry quarry
#

What kind of game is this

wintry quarry
topaz mortar
#

the server is a C# UGS Cloud Code Module

#

yeah my bad

slate haven
hasty sleet
# slate haven didnt try that

And the majority of performance bottlenecks, if real, come from expensive code put inside of Update() or FixedUpdate() loops

hasty sleet
hasty sleet
#

GetComponent should probably never be called in any Update cycle

rich adder
slate haven
#
    {
      
        foreach (string tag in tags)
        {
            items.AddRange(FindObjectsOfType<GameObject>().Where(go => go.tag == tag).ToList());

        }
       
      

        if (pManager != null)
      
           {

            if(gameObject != null)
            {
                if (pManager.LaneSpeedIncrease == true)
                {
                    Speed = 10f;
                    MoveCars(10f);

                }

                if ((pManager.LaneSpeedReset == true) || (!pManager.LaneSpeedReset && !pManager.LaneSpeedIncrease))
                {
                    Speed = 5f;
                    MoveCars(5f);

                }

                else
                {
                    Speed = 5f;
                    MoveCars(5f);
                }
            }
            
        }
 
    }```
hasty sleet
slate haven
#

whats wrong here

hasty sleet
#

Update is run every single frame, so the faster you render, the more work you have to do

#

If you run 244 fps, then you have to do the loop 244 times, which, if it is enough work, will drop your frames

slow pecan
#

im guessing it needs fixedupdate?

hasty sleet
#

Like an employee who finishes all their work and is given more work by their boss

slate haven
#

what else approach should i do

hasty sleet
#

The logic itself needs to be restructured to only be called as-needed

#

Reduce duplicate logic. The precise approach depends and would need more analysis to figure out exactly what you're trying to accomplish

cosmic dagger
# slate haven whats wrong here

you're getting every GameObject in the scene, then searching for a specific tag, and converting that to a list, every frame. ouch!

hasty sleet
#

For example, why do you set your cars' speed every single frame?

slate haven
hasty sleet
#

The only thing that should be in Update, generally speaking, is inputs

#

Because players want responsive controls 100% of the time

#

But logic should be done at worst in FixedUpdate, and at best exactly when needed. Think of event-based systems, like if a car crashes into another car, then recalculate its speed

cosmic dagger
hasty sleet
#

But don't do math if nothing changed. Do math when needed.

slate haven
#

so should i paste this code in fixedUpdate() or somewhere else where its actually more needed?

#

to reduce the frames it does calculate

#

i mean to ask in what situation shall i use fixed update

cosmic dagger
rich adder
cosmic dagger
#

fix this part:

foreach (string tag in tags)
{
    items.AddRange(FindObjectsOfType<GameObject>().Where(go => go.tag == tag).ToList());
}
hasty sleet
# slate haven where do i put this part
 void Update()
    {
      
        // This is the most expensive part
        foreach (string tag in tags)
        {
            items.AddRange(FindObjectsOfType<GameObject>().Where(go => go.tag == tag).ToList());
        }
      

        if (pManager != null && gameObject != null)
        {

            if (pManager.LaneSpeedIncrease == true)
            {
                Speed = 10f;
                // This is likely going to cause unintended speed fluctuations since Update
                // is based on render speed, not a fixed speed like FixedUpdate()
                MoveCars(10f);
            }

            if ((pManager.LaneSpeedReset == true) ||
                (!pManager.LaneSpeedReset && !pManager.LaneSpeedIncrease))
            {
                Speed = 5f;
                MoveCars(5f);
            }
            else
            {
                Speed = 5f;
                MoveCars(5f);
            }
        }
    }
#

I refactored

slate haven
hasty sleet
#

The "which part" is "all of it"

#

Since Update is generally best-used for player inputs

#

You need to explain your logic before we can prescribe solutions

#

Personally, I would make each car move itself.

slate haven
#
{
    items.AddRange(FindObjectsOfType<GameObject>().Where(go => go.tag == tag).ToList());
}

Where do i actually put this part? Cuz I really need every item to be added in list every time an item comes

hasty sleet
#

Cars are entities that can handle their own business

eternal needle
#

is there also more code than this? because this items collections would be increasing every single frame...

hasty sleet
#

The code needs to be fundamentally restructured.

cosmic dagger
hasty sleet
#

Cars should move themselves, so each car should have a script dictating its speed. If all AI cars have the same speed, then create a component AICarController and let it decide how fast to go.

cosmic dagger
hasty sleet
#
  1. Avoid using tags if possible
  2. Do not put expensive logic in Update
  3. Only perform calculations when needed
slate haven
#

My game has dynamic lanes, sometimes its 2 , 4 ,6. SO when a lane is removed (by player's actions), the laneless items appear to be on ground, I want to manage them

#

Like if i can remove them from the list, or make their speed such that they move out of the scene with the removed lane

hasty sleet
#

public class NPCCar
{
  public int Speed = 10;
  
  private void FixedUpdate()
  {
    // Move down by {Speed} units every fixed interval of time
    transform.Translate(Vector3.up * -1 * Speed);
  }
}
hasty sleet
slate haven
hasty sleet
#
Lane1
| - Car1
| - Car2
| - Car3

Lane2
| - Car1
| - Car2
| - Car3

Lane3
| - Car1
| - Car2
| - Car3

Lane4
| - Car1
| - Car2
| - Car3
#

Each car can be stored hierarchically under a "Lane" game object.

slate haven
hasty sleet
#

If the car collides with an out-of-bounds box, then destroy the car

hasty sleet
slate haven
hasty sleet
#

Why are you measuring the speed of the lane and not just the speed that the player is going, which should be the same speed?

#

If player goes up 10 units/second, and the items are not moving, then the items should appear to move downward at 10 units/second while the player appears stationary

slate haven
#

the player isnt moving tbh

#

its the items that are scrolling down

hasty sleet
#

Exactly, so the player's actual speed is instead applied to other items

#

The player's speed is the source of speed for other items

#

So instead of associating items to lanes

#

Just let the items exist, and the player's speed can be used as the basis for calculating the speed of other items, whether they're on a lane or not

slate haven
#

i mean the player doesnt have any speed, we can either move it left or right thats it

hasty sleet
#

public class StationaryItem
{
  private PlayerCar _playerCar;
  private void Awake()
  {
    // This assumes PlayerCar is attached to a GameObject called Playercar
    _playerCar = GameObject.Find("PlayerCar").GetComponent<Playercar>();
  }
  private void FixedUpdate()
  {
    transform.translate(Vector2.down * _playerCar.Speed);
  }
}

public class MovingItem
{
  private float _speed;
  private PlayerCar _playerCar;
  private void Awake()
  {
    // This assumes PlayerCar is attached to a GameObject called Playercar
    _playerCar = GameObject.Find("PlayerCar").GetComponent<Playercar>();
  }
  private void FixedUpdate()
  {
    transform.translate(Vector2.down * (_playerCar.Speed + _speed));
  }
}
#

The player doesn't really have an actual speed, but it is the sole controller of the speed of every other object

slate haven
#

so ur telling that i should associate speed of every item to the playercar.speed

#

whenever they are moving

hasty sleet
#

Kind of

#

Every single object moves downward only because the player is "moving" upward

#

So at the start of their existence, they should locate the Player, determine how fast the player is moving, and then move downward every FixedUpdate

slate haven
hasty sleet
#

Yes, the player is stationary and the items move downward

slate haven
#

yes

hasty sleet
#

Since all of the items move downward at the same speed, they must have one source of truth

#

The one source of truth is, in essence, how fast the player is (by illusion) moving upwards

#

Each individual object should handle its own speed

#

Or you can just add a component that makes each object fall

slate haven
#
    {
        transform.position -= new Vector3(0, Speed * Time.deltaTime, 0);
        if (transform.position.y <= -12)
        {
            if(gameObject != null)
            {
                items.Remove(gameObject);
                
                op.DeactivateGameObject(gameObject.tag, gameObject);
            }
           

        }
    }```

This is how every item (car, pickup, coins) are moving downward
hasty sleet
#

They should not be controlled in an Update loop, but in a FixedUpdate loop with no logic beyond a simple transform.translate(go downwards)

#

that is convoluted

#

I don't like that function

slate haven
#
    {
        if(pickup.LaneSpeedIncrease == true)
        {
            laneScrollSpeed = 5f;
            laneMeshRenderer.material.mainTextureOffset +=
           new Vector2(0, laneScrollSpeed * Time.deltaTime);

            
        }

        if((pickup.LaneSpeedReset == true) || (!pickup.LaneSpeedReset && !pickup.LaneSpeedIncrease))
        {
            laneScrollSpeed = 1f;
            laneMeshRenderer.material.mainTextureOffset +=
          new Vector2(0, laneScrollSpeed * Time.deltaTime);

          
        }

        ```
This is how the lanes/ground scroll
hasty sleet
#

It does too many things

#

aaaaaaaaa

#

too much logic

#

There should be one single Speedcontroller

cosmic dagger
#

it's fine to move the objects in Update, especially since they're manipulating the transform which doesn't use the physics engine . . .

hasty sleet
#

Everything else that is meant to scroll down should observe the one source of truth and scroll down

#

Moving in Update doesn't make a lot of sense because you can just do it in FixedUpdate which is what physics handling is for

#

transform doesn't use physics but the point isn't just to not use physics, but to prevent unnecessary math

#

I suppose it works but it should be avoided by default

#

Movement logic goes into FixedUpdate and input logic goes into Update

slate haven
#

I understand

hasty sleet
#

This:
if((pickup.LaneSpeedReset == true) || (!pickup.LaneSpeedReset && !pickup.LaneSpeedIncrease))

Should be this:
/*nothing here*/

slate haven
#

but coming to the main point

#

Like how do i actually manage the LaneLess Items?

hasty sleet
#

Laneless items still scroll down, yes?

slate haven
#

but at a different speed

#

ig

hasty sleet
#

Why a different speed?

slate haven
#

different script for the lane, different script for item movement

#

cuz in lanes, mesh renderer is involved

hasty sleet
#

Regardless of why, you can give them a separate component that makes them scroll down

slate haven
#

items, just transform

hasty sleet
#

Give lanes a ScrollLane component

#

Or have a LaneController component that handles how lanes scroll

#

And then give items an Item component with a MoveDown function, or perhaps a ScrollDown component that scrolls downward

#

Perhaps create a ScrollDownManager that manages all items as they scroll down

#

And each FixedUpdate, move the items down by some fixed speed

slate haven
#

which handles its movement

hasty sleet
#

Yes, if that's how it is now, then that works

#

As long as you extremely simplify that logic

#

It's like a car, right? You just hit the accelerator pedal, but the car just goes at its normal speed

#

If it's at 50 mph, it doesn't check to see how fast it's going

#

It just continues to go its speed

#

And if you want it to go faster, you change the speed

#

Lanes shouldn't check how fast to go in every frame; they should just go their assigned speed, and if a special event occurs, then the speed should be changed

slate haven
#

so in a conclusion, I should have a single script which has the same speed for the lanes, and the items on it as well
1.) If the item is on the lane, no worry, they go out downward at the same time
2.) if not, just deactivate it

hasty sleet
#

I do not quite understand what you mean by "they go out downward at the same time"

#

Lanes and items should go downward at the same speed, as far as I am understanding

#

I don't know why you would necessarily deactivate an item that's not on a lane, because how did it get there in the first place?

#

Also, I would destroy it instead of deactivate since I don't want to leave memory in the scene

hasty sleet
#

That's a good optimization technique but I think you might have bigger fish to fry first

#

Up to you if you want to implement it

#

I think it might be premature optimization

#

Fully up to you

slate haven
#

the items spawn from the very above in a random distance

#

thats why i told that some items might not be in the lane

hasty sleet
#
  1. Each lane should decide to go downward at the same speed every FixedUpdate
  2. Items that meet criteria for being "invalid" can undergo your deinitizliation/deactivation procedures
hasty sleet
#

And these should be kicked off by a particular event

#

They shouldn't check for the event

#

Like you don't check if someone's knocking at your door every second of your existence; you simply wait until you hear a knock

#

The lanes and items should continue to scroll until something tells it to do something else

slate haven
#

got it

#

also

#

how do i check whether the item is on the lane or not

#

any method()?

hasty sleet
#

Are you checking if it's on (a) lane, or (any) lane?

slate haven
#

any

#

if it isnt on any lane, destroy

hasty sleet
#

You can check for collisions

#

And collisions are okay to check for in FixedUpdate

#

Well, there's something called OnColliderEnter

slate haven
#
                bool isWithinBoundsRightLane = rightLaneCollider.bounds.Contains(go.transform.position);

                      if (isWithinBoundsLeftLane || isWithinBoundsRightLane)
                      {
                         

                      }```
hasty sleet
#

Which is a built-in function that triggers whenever something enters a collider.

slate haven
#

this?

hasty sleet
#

You seem to have implemented it manually

slate haven
#

oh

hasty sleet
#

I recommend using the built-in functions instead

slate haven
#

okayy man

hasty sleet
#
using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour
{
    void OnCollisionExit(Collision other)
    {
        print("No longer in contact with " + other.transform.name);
    }
}
#

^ this is super neat

#

"Not in contact with lane anymore; uh oh, gotta deactive"

slate haven
#

also where did u learn all of it?

hasty sleet
#

By solving countless problems over and over and over

#

And getting things wrong over and over

#

Doing exactly what you are doing now for a few months

#

I also have a computer science background

slate haven
#

Yeah same

#

But I started late

#

I want to gain more knowledge

hasty sleet
#

I am midway in my career, but better late than never. You can learn anything given enough time

slate haven
#

yeah

#

Thanks!

hasty sleet
#

No problem!

cosmic dagger
#

why check if it's > 100 when you clamp it beforehand? also, by using Time.time, the longer the game is played, the faster Thirst will reach 100. basically, playing the game for longer than 10 seconds will instantly set Thirst to 100+ . . .

queen adder
#

im new to coding don't know much in detail

#

so i should use time.deltatime ?

slender nymph
#

oh and don't cross post because i already answered you in another channel

cosmic dagger
#

i believe you want to add deltaTime here . . .

queen adder
#

ok

onyx tusk
#

when trying 2 create file at */myLogs/{DateTime.Now + ".txt"} i have UnauthorizedAccessException

#

what can i do for don't get it?

real rock
#

That would mean Unity doesn’t have permissions to write a file there

#

(And any subfolder of that)

faint oasis
#

Hi all, I'm playing with DOTS right now. I already have a spawner with it's authoring script and many inputs (number to spawn etc)
It works in the editor when i press play but after building the authoring is of course empty. How is it tipical to set default arguments for the authorings? Reading from a file, database? Setting an UI from scratch for each one of the authorings? is there any "ready to go" solution? It seems like a very common problem for everyone right?

onyx tusk
#

Application.persistentDataPath + @"\\myLogs\\"

keen dew
#

\\myLogs\\ is not a valid path

#

use Path.Join and you might need to create the myLogs directory if it doesn't exist

mighty basalt
#

i have this really disgusting code that doesnt quite work like i want it to. i have 4 tilemap presets and want them to procedurally generate as the player walks through the world in my top down 2d game. however i cant make it work so the map generates the right place. currently it just places them left, right, up or down from the starting position. i tried to fix this with the "PlayerY" and "PlayerX" variables but that did not work. the way ive done this might have been suboptimal, so if anyone has ideas on how to fix it, or rework it somewhat quickly/easily id love to hear it
https://pastebin.com/saDJHG4s

topaz mortar
#

Alright so to clarify my question from earlier:
My client is Unity, my server is non-persistent, a UGS C# Cloud Code Module saving data to UGS Cloud Save (json)
My Inventory has a limited amount of itemslots, that hold an item, it also remembers which item is in which itemslot
My server generates items and saves them to cloud save
What kind of structure should I use to properly save these items?
I'm thinking to save all of the items in a single json string/array, and then next to that, save a 2nd json string that remembers which item is in which itemslot. So that when I'm making a new item, the server does not have to loop through all existing items to find an open itemslot

storm pine
# mighty basalt i have this really disgusting code that doesnt quite work like i want it to. i h...

Maybe you have to change a little your scope, more than just spawing a tile close to you I think is better if you check the direction where the player is going ans see if there is a tile on that direction. Other improve that you can use is to have a HasSet<Vector2Int> so you can check efficiently where are tiles generates and where not. Something like this, I haven't test it, is just to give you some idea of my approach: https://hatebin.com/zgspupkzce

hallow iris
#

Question dose any one know how to make water in unity?

copper pumice
hallow iris
copper pumice
#

You will need some scripts to handle bouyancy.

#

Basically you want to add a force if an object is under a y level.

stone saddle
#

stupid question, but how do I access a variable from another script?

copper pumice
#

Make sure it is public.

stone saddle
#

thank you

hallow iris
copper pumice
hallow iris
#

thanks

copper pumice
#

In this tutorial you'll learn how to set up boat movement and dynamic water physics in Unity.

Check out my devlogs: https://www.youtube.com/playlist?list=PLXkn83W0QkfmQI9lUzi--TxJaOFYIN7Q4

⎯⎯⎯⎯⎯⎯

Catlike Coding's article about shader-based vertex manipulation and Gerstner waves: https://catlikecoding.com/unity/tutorials/flow/waves/

Discord s...

â–¶ Play video
tough cave
#

Can i not use Monobehaviour classes, in a class that is dirived from the parent class? 😮
Got a abstract class, with a student thats linked with the Char class.
But my OnTriggerdEnter is not working. Its not detecting a touch.

 public abstract class Character: MonoBehaviour
 {

  public class Student : Character
  {
      public void OnTriggerEnter2D(Collider2D collision)
      {
          Debug.Log("entering");
          if (collision.gameObject.tag == "Player")
          {
           
              popupDialog.IsInRangeForDialog(true);
          }
      }

      public void OnTriggerExit2D(Collider2D collision)
      {
          Debug.Log("leave");
          if (collision.gameObject.tag == "Player")
          {
             
              popupDialog.IsInRangeForDialog(false);
          }
      }
hallow iris
copper pumice
# hallow iris legit life saver

Keep in mind that this is a rather complicated topic and you might need to change some stuff and read up a bit more on it. The term you want is bouyancy force.

storm pine
tough cave
#

oh thanks.. :{ oopsies...

storm pine
mighty basalt
stone saddle
teal viper
topaz mortar
stone saddle
#

awesome, thank you

storm pine
# mighty basalt what are hashsets? also i tried running your code and it spawns a prefab on the ...

Set is a data structure where you can only have inside one of each value. For example Set<int> = {1,3,5,6}, if you try to add a 2 it will be added but if you try to add a 3 it won't. The hash part is the way the data are internally stored, that's the efficient way to make it access any value in O(1) (order 1, almost at the first try), so even if you have a lot of data inside that set you will always have it so fast, you don't have to check all content on a for loop, as you do with array and list. You can also use hash with other structures.

stone saddle
#

the object that the first script is attached to? (the script trying to access the function)

topaz mortar
storm pine
stone saddle
topaz mortar
#

the component is the 2nd script that has the function you want to access

languid spire
#

it is the Game Object

stone saddle
#

oh right yeah

#

and then the last part is the function?

topaz mortar
#

.Health is the variable on the 2nd script that you want

languid spire
#

please be careful of your terminology, object, Object and GameObject are very different things

stone saddle
#

confusing

topaz mortar
#

yeah it's not the best example

#

let me think for a sec

languid spire
#

only if you use the wrong one

stone saddle
#

I'm getting an error that says GameManager (the thing with the script I want to access) doesn't exist in the current context

topaz mortar
#

int damage = Inventory.GetComponent<Weapon>().Damage;

teal viper
languid spire
#

ok,
object is a C# object
Object is a Unity object
GameObject is a Unity object of type GameObject

eternal falconBOT
stone saddle
#

I'm guessing not lol

stone saddle
languid spire
#

GameManager sounds more like a class than an instance of a class

storm pine
stone saddle
#

public

#

I tried to send the code and it's just a big block

#

I can't send it

topaz mortar
#

send the line where you have the error

stone saddle
#

GameManager.GetComponent<CollectableIncrementor>().Increment();

#

but without spelling errors

topaz mortar
#

does your GameManager have a component named ColleactableIncrementor?

stone saddle
#

yeah that's the script I'm trying to access

#

attached to the GameManager

languid spire
#

what Type is GameManager ?

stone saddle
#

type? I'm not sure

#

it's an object in unity

#

with some scripts attached

teal viper
eternal falconBOT
stone saddle
#

I don't have Internet access and it's hard to type out on mobile

#

I tried and it was just a big block

teal viper
#

Well, we can't help you much if we don't have access to your error or code.

stone saddle
#

yeah sorry

#

I don't know what else to do

teal viper
#

Maybe do something to have internet on the PC.

stone saddle
#

I'm in school, no Internet here

#

I'll come back later with internet

languid spire
stone saddle
#

I fear my laptop will eat my remaining data in 2 seconds

burnt vapor
#

If you want to be helped you will have to share relevant context

mighty basalt
#

like i guess i would find they way the player is moving, look for the nearest empty space and if thats within a certain range, i would add a new tile there? but how would i code that

storm pine
#

You will need and update with a method to create tiles around you. something like this: https://hatebin.com/ihtqleyhim
I'm just considering the four basic directions but maybe you want to check all around the player, even the diagonal, so you just have to add like new Vector2Int(1, 1) for Up-Right when you initialize your directions array

queen adder
#
 
    private void Update()
    {
        
        if(TimeInGame.TimeInGame_ >= 9)
        {
            Coffee_Function();
        }
     
    }

    public void Coffee_Function()
    {

        agent.destination = CoffeeTable.position;
        animator.Play("Walk");
        if (agent.remainingDistance < 1)
        {
            animator.Play("Drinking");
        }

    }
#

its not going to the location

topaz mortar
#

you're only showing an animation, you're not actually moving anything

queen adder
#

agent.destination

#

it works when i type it in update

#

but not like that

#

can you help please

topaz mortar
#

are you resetting the TimeInGame so Coffee_Function is only called once instead of every Update?

queen adder
#

its called only once at 9

#

i don't know what resetting means here

#

im new to coding

#

right now the time is not resetting if that is what you mean

#

its basic

topaz mortar
#

if it's working when you put it in the Update function, it's because it gets called several times
but if you change TimeInGame_ back to less than 9, your Coffee_Function will only get called once

#

but again, I don't see any code that moves anything

honest haven
#
         {
             if (activeBattlers[i].gameObject.activeInHierarchy)
             {
                 activeCount++;
             }
         } ```whats the best way to count this, currently its in update, but it just goes up and up each frame
#

count should only be 4 on start

burnt vapor
languid spire
eternal falconBOT
burnt vapor
honest haven
burnt vapor
#

This is not the type of thing you should worry about

#

But if you are able to be imprecise occasionally, you can also consider only counting once every 10 frames for example

#

But again, not a lot of reason to improve performance this way, because the difference is negligible

honest haven
#

i think i might just add it out of update, but at the same time thought there might be away without setting a bool

burnt vapor
#

You can also make it a property

void thicket
#

You can increase the counter when object becomes active and decrease when deactivated

burnt vapor
#

Then just put this logic in there and count when the property is called

burnt vapor
#

More boilerplate OnEnable/OnDisable which I think will just complicate something that won't become any better this way

void thicket
#

You would want to consolidate that kind of logic anyways

burnt vapor
#

Yes, though you now delegate the logic to other things and you should probably introduce events to avoid coupling things together

#

So now it becomes worse again

void thicket
#

Inject dependency 😄

tawdry mirage
#

if i have 1000 tiles of which 10 are alwaysFalse:

{
    private int one = 1;
    private bool alwaysFalse = false;

    public TileOld(bool alwaysFalse = false)
    {
        this.alwaysFalse = alwaysFalse;
    }
    public bool Check(int two)
    {
        if (alwaysFalse) return false;
        return one == two;
    }
}```
that mean in 99% cases 'if' does useless work
#

so, if i do:

{
    private int one = 1;
    public func<int, bool> Check;

    public Tile(bool alwaysFalse = false)
    {
        if (alwaysFalse) Check = returnFalse;
        else Check = isEqual;
    }
    private bool isEqual(int two)
    {
        return one == two;
    }
    private bool returnFalse(int two)
    {
        return false;
    }
}```
what are nuances here?
#

i read docs, but i'm not smart, it says it is slower and will generate garbage

void thicket
#

It will allocate when Tile is created sure, but that's not the main concern

tawdry mirage
#

what is main concern?

#

i thought about inheriting and overriding it, but this looks prettier

void thicket
#

You are paying for function call, just to avoid conditional check

#

Function call is way expensive, to be clear

tawdry mirage
#

so, how to dodge the conditional check?

void thicket
#

You don't

tawdry mirage
#

gamedev is full of frustration

void thicket
#

I mean the performance we are talking here is negligible for 99% of time if not more

tawdry mirage
#

it's part of pathfinding, so i would squeeze maximum

void thicket
#

High level concepts like delegate or virtual function are not going to help you here

wintry quarry
#

This means more complications elsewhere no doubt

tawdry mirage
#

but i put them in same collection to skip other if checks

wintry quarry
#

Programming is about tradeoffs

void thicket
#

Did you actually run performance profile for this?

#

If not, do that first

#

Benchmark I mean

tawdry mirage
#

setting it up

brave compass
tawdry mirage
#

so, the idea is basic branching is already good with all 'hidden' optimizations, i just need to reduce basic coding to less amount of basic coding, not to more of high-level stuff

#

ofc it all depends on my unique situation

stuck palm
#

why is this in the visual scripting namespace

void thicket
#

The instance should be GO or Component not UnityEngine Object

stuck palm
void thicket
#

Sure

final totem
#

is system the standard library for csharp?

wintry quarry
strong hound
#

Hello ! I'm new to unity, I was wondering : what's the most comon / efficient way to store data for a game ? In my case, its just for saving scores and usernames (not even a password, its a simple project). I was thinking about json but I'm not sure if its the right thing to do

wintry quarry
strong hound
strong hound
#

Isn't it better on PlayerPrefs ?

languid spire
timid bridge
burnt vapor
# strong hound Isn't it better on PlayerPrefs ?

Not really. PlayerPrefs is the simplest, easiest to implement, and most straightforward solution. However, for any published games you should really not use it and instead use a text file. Writing data to a file is not hard and I would argue encrypting data is also fairly simple if you know what you are doing.

#

The issue with PlayerPrefs is that you save data as registry keys. The registry is really not used for that sort of thing and mainly saves system and application configuration data.

#

But if you really want to use Registry keys then you can just use the base system and save json under a string value.

strong hound
#

I see, I think I'll go with the txt file solution then, thank you all for the ressources and the answers

#

It looks easier for me to implement it, already done that on a lot of c# project

tough cave
#

What is best practice for creating popups using canvas's?
Got a friendly discussion on using a canvas as a prefab, vs keep it inside the hierarchy and set it as unactive/active...
I switched his code from doing setActive = false/true, to Instantiate(prefab gameobject).

    public abstract class IPopup: MonoBehaviour
    {
        // Contains popup object
        public GameObject popUp;
        // Static variable to check if popup is already instantiated
        private static GameObject instantiatedPopUp;

        // These methods are virtual in case the implementation needs to differ.
        public virtual void ShowPopup()
        {
            // Check if the popup has already been instantiated
            if (instantiatedPopUp == null)
            {
                // Instantiate the popup if it hasn't been instantiated
                instantiatedPopUp = Instantiate(popUp);
            }
        }

        public virtual void HidePopup()
        {
            // Check if the popup has already been instantiated
            if (instantiatedPopUp != null)
            {
                // Destroy the popup if it has been instantiated
                Destroy(instantiatedPopUp);
                instantiatedPopUp = null;
            }
        }
    }
    public abstract class IPopup: MonoBehaviour
    {
        // Contains popup object
        public GameObject popUp;

        // These methods are virtual in case the implementation needs to differ.
        public virtual void ShowPopup()
        {
            popUp.SetActive(true);
        }

        public virtual void HidePopup()
        {
            // These methods are virtual in case the implementation needs to differ.
            popUp.SetActive(false);
        }
    }
}
#

I thought Unity is all about prefabs and instantiating them when needed, and try to get as least as possible inside the hierarchy.
Its clearer due not having 5 canvas's stacked over eachoether.
But he mentioned its easier/less heavier if its allrdy there from the start of the game, and all u gotta do is set active/unactive

timid bridge
tough cave
#

Argumentation?

#

ease?

wintry quarry
#

it avoids GC, which is better for performance.

#

You can reuse a single popup object if possible too

timid bridge
#

for me its easier to just disable or enable popups instead of Instantiate it every time and also destroy it every time.

paper vigil
wintry quarry
#
  • Canvas doesn't have alpha
  • That will block raycasts for the event system (which may or may not matter in your game)
paper vigil
wintry quarry
#

isn't that just a one time cost though?

tough cave
#

But we plan to have 3/4 popups, and a startard UI. U all use 1 canvas's, and put everything inside there? O_o. Or have 4 canvases with each their use for SRP?

wintry quarry
#

Compared with continuing to render the UI even when it's invisible?

paper vigil
#

It is a one time cost, but when you have a huge menu with a lot of different buttons/components, it actually is very heavy to redraw all that to enable or disable one component. I guess it depends on the individual situation

tough cave
#

Its not for menu, its for an level where students have questions, which will generate a Popup where the player can pick/choose options based on the scenario. So its a dynamic popup with different options.

And i shouldnt see setactive like the same kidna thing if i alt-tab a game? its like running on the background, and that can be bad if u have like 4/5 popups on the background waiting to be activated over the level.

swift crag
#

I have a pretty large menu. I deactivate everything except the currently visible screens.

#

I also lazily create things like settings screens

tough cave
#

For a menu I would understand cuz its static.

#

It doesnt change over the map/ at different locations.

swift crag
#

well, this menu is also used to display dynamic information

#

like when you configure an entity

#

lazy creation is very helpful there; I can avoid creating 20 different screens if I'm only going to click into one or two of them

whole narwhal
#

I need a timer for my game. Is there a c# script somewhere I can copy?

rich adder
#

if you plan on doing development I suggest you get familiar with such a tool

wintry quarry
#

for example here's a simple timer, but who knows if it's useful for you:

float timer = 0;

void Update() {
  timer += Time.deltaTime;
}```
#

It's best if you give details about your specific requirements.

hallow totem
#

Why am I getting this error?

    {
        LookAtPlayer();
        float distanceFromPlayer = Vector3.Distance(player.position, animator.transform.position);
        if (distanceFromPlayer > stopAttackingDistance)
        {
            animator.SetBool("isAttacking", false);
        }
    }```
rich adder
#

in animator

#

it has no idea what isAttacking is

polar acorn
hallow totem
#

Ugh... The parameter in the Animator wasn't camel case. Thanks.

whole narwhal
#

I found this one video but I got 2 issues. Let me go one at a time. I cannot see the text object in my game view

#

For My timer*

rich adder
whole narwhal
#

Sorry. I'm trying to add a simple timer for my game. I copied off a youtube video for the bulk of it but the timer isn't going down at all and instead only shows the initial string format from my code (I'll send a picture) any help is appreciated I've only been using unity for 3 months

rich adder
#

again. Show relevant Code and Screenshots of scene/ text setup

whole narwhal
#

It's sending

polar acorn
rich adder
#

also dont screenshot code

#

!code

eternal falconBOT
whole narwhal
#

Im on school computers that block discord

rich adder
polar acorn
whole narwhal
#

I'm seeing the timeless variable go down but the in-game text isn't changing

#

And the Instructor is just as inexperienced as I am

polar acorn
#

Then why are they instructing

whole narwhal
#

The old teacher took a new job

rich adder
#

2020s Instructors be like

whole narwhal
#

He is actually a game art teacher

#

Barely passed the unity program cert as it is lol

rich adder
#

anyway could you show what that error is btw ?

swift crag
whole narwhal
#

The null obj It's fairly irrelevant my game still runs fine.

#

Just the timer I'm trying to figure out. The text isn't updating

polar acorn
whole narwhal
#

Different red ! He was asking about ^^^

#

Trying to add the timer (screenshots above) timerLeft variable is going down but the text isn't updating with it

rich adder
#

how are you checking the values going down for timeLeft

whole narwhal
#

In the inspector

outer scarab
#

Hello, I have grid and the grid has a nested Tilemap object.
A script is attached to the Grid, how can I access the Tilemap from it?

rich adder
rich adder
outer scarab
#

Also, if I want to get the position of a cell (e.g. to place a sprite on it), do I take the WorldToCell from the grid or the tilemap itself?

rich adder
#

ideally make a filed in the inspector and link it there

outer scarab
polar acorn
outer scarab
#

That's of course the easiest solution, but the Tilemaps are generated dynamically and they are never the same.

rich adder
#

cant you just store the Tilemap reference when you create/generate it ?

#

event could also work

#
public event Action<Tilemap> OnTilemapGenerated
...
OnTilemapGenerated?.Invoke(generatedTilemap)```
stuck palm
#
 void SelectFirstItem()
    {
        if (!EventSystem.current.currentSelectedGameObject) {
            var child = GetComponentInChildren<Selectable>();
            if (child)
            {
                Debug.Log("SELECTING: " + child.name, gameObject);
                child.Select();

Does this call OnSelected() on the child?

#

this doesnt seem to be getting called. SelectFirstItem is called onenable

fading rapids
#

does anyone know what the problem here is

stuck palm
fading rapids
#

oh wait

#

that matters?

stuck palm
#

yeah

fading rapids
#

didnt know ty

stuck palm
polar acorn
stuck palm
#

yeah

fading rapids
#

oh

#

didnt know that

#

ty its working now

whole narwhal
#

Nope just updates once to (0:00) : (1:00) and stays there

#

Sry for late response ^^^

rich adder
whole narwhal
#

I can try tomorrow class ended. Again no discord on school computers and the game is only stored on them

worthy tundra
#

i found out i cant use Invoke and StartCoroutine in scriptable object, is there a way for me to time functions in scriptable object?

wintry quarry
worthy tundra
# wintry quarry drive the timed part from a MonoBehaviour

idk if that can be done, i will explain.
basically im making an enemy ai system and each behavior (attack, chase, patrol, dodge) is each own SO class.
in the enemy script i have a logic system to determine how to use each SO.

so basically:

if (Condition for specific SO is met)
SO.DoAction();

and in the SO:

void DoAction()
// does the action

what i want is a melee attack that will, when called, wait a charge period, then attack, then wait a recovery period

wintry quarry
#

it can be a singleton DDOL
the SOs can interact with the singleton to run coroutines etc.

timber tide
#

You mean that it's destroying instantly and you dont want that to happen? It need to set up some coroutine to delay the clean up.

polar acorn
#

Set your particle effect to destroy itself upon completion

worthy tundra
#

add a script to the explostion vfx that destroys itself after some time

stuck palm
polar acorn
#

The Stop Action

rich adder
timber tide
#

how does that work with child systems

#

or I guess you would do a on hit -> particle system explosion

wintry quarry
timber tide
#

but I guess another issue is also if you were pooling the particle systems

worthy tundra
# wintry quarry It can be done. Basically keep a MonoBehaviour around to drive this system

i think you gave me another idea.
the SO already has a reference to the monobehavior that is calling it, maybe i can just add a wait function to the monobehavior, and then after that function is over it will call another SO that will do the attack, and so forth and so forth...

basically in the monobehavior:

enum Action.....
void WaitTime(Action action, float timeUntilAction)
switch (action)
case ActionA:
Invoke("ActionA", timeUntilAction);

wintry quarry
worthy tundra
#

im gonna do that and tell you how it went but first i must tend to my hunger

wintry quarry
#

the lifecycle of the coroutine is tied to that MonoBehaviour instance

worthy tundra
wintry quarry
#

it can often be helpful to have a dedicated MonoBehaviour instance for this

wintry quarry
rich adder
#

Invoke cannot be stopped individually, passed parameters etc

worthy tundra
worthy tundra
# wintry quarry Invoke has the same limitations

well i plan for the enemies to be morons so i can just make sure that if they chose to wait for an action they are now committed to it and cant cancel an action, so just a bool to not allow them to call another action while they are waiting

stuck palm
wintry quarry
#

just call Emit on the ParticleSystem instance on the clone

wintry quarry
#

sure or just make the prefab of type ParticleSystem in the first place

#

or have a proxy script on it that does the actual work of calling Emit

#

Ok?

#

yes that's what we're discussing

stuck palm
wintry quarry
#

well what parameter are you giving it?
How many times are you calling it?

rich adder
#

what does your emission settings look like

stuck palm
rich adder
#

im talking about the Particle system Emission settings

#

thats a line of code

#

10 rate over time might be why so many

wintry quarry
#

Can you show the inspector

rich adder
#

well how many appear now..

stuck palm
#

Text Button inherits Button

wintry quarry
rich adder
#

dont u want Burst then ?

#

also show where you are calling Emit btw

stuck palm
wintry quarry
# stuck palm

Ok well "SelectOnEnable" is not attached to this object

#

so that's why your code isn't running

rich adder
#

did you try switching it to burst instead?

stuck palm
rich adder
#

in Emission section

#

nvm
emission should behave just as burst now that i remember

wintry quarry
rich adder
#

yeah u dont need burst my bad, been a while since I've used ps

stuck palm
#

i thought that calling child.Select() would call OnSelect() on the child being selected

wintry quarry
#

Only actually selecting it will do that

stuck palm
#

if i go back and forth within the buttons it works as normal

#

but at start it fails

wintry quarry
#

Yes because that actually selects them

stuck palm
#

is there anyway to manually call on select

wintry quarry
#

yes EventSystem.current.SetSelectedGameObject(myObject);

wintry quarry
stuck palm
wintry quarry
#

if you only want to manually emit particles, turn off all emission in the inspector

#

incl. setting rate over time to 0

mighty basalt
#

this is my script https://pastebin.com/dz8f65vc
it instantiates random prefabs of tilemaps as the player moves around. however, after walking just a little bit around, unity chrashes. hypothetically it could be another script but im positive its this one. i believe its some optimisation issue, so if anyone likes optimisation problems id love some help on how to optimise this. the instantiated tilemaps also never get deleated no matter how far away the player is, which i probably also should add, but i dont think thats whats causing the crash

wintry quarry
#

well yeah there's literally nothing in this script that tries to call Emit on the instantiated object

#

You saved the clone to a variable:

GameObject ExplosionClone = Instantiate(ExplosionEffect, transform.position, transform.rotation);```
But then you completely ignored it
rich adder
#

same way you access other components

#

also if thats all that ExplosionClone does, can also just store it as ParticleSystem

polar acorn
#

If ExplosionEffect is of type ParticleSystem, then Instantiate will return a reference to the particle system

frosty hound
#

That is how you do it.

#

If it's not doing anything, then your particle system isn't completing. Make sure it's not looping for starters.

rich adder
#

stop action was none ofcourse it didnt

stuck palm
#

why arent these showing up?

wintry quarry
#

I think it's usually better to just make a separate component

#

rather than deriving from Button

#

and use an EventTrigger to hook up the events

#

or IPointerClickHandler/IPointerEnter/ExitHandler etc

stuck palm
#

is there no way to add stuff to the custom inspector?

polar acorn
#

Nothing in this code seems to be doing any of that

#

Put the box on an object that doesn't spin

#

And then making the spinning thing a child of that

mighty basalt
polar acorn
#

So move the Hitbox object instead of Player

mighty basalt
polar acorn
# mighty basalt https://pastebin.com/xN7GCf9r

I don't think this would go infinite. Pretty sure OnTrigger functions run on disabled objects specifically so you can do something like this. Still, you can eliminate this as a possibility by commenting out the OnTriggerExit function and seeing if it still crashes

mighty basalt
#

do you think it would be necessarry to make the game delete tilemap prefabs that are far away, or will that not make any meaningful difference

eager wolf
#

how do i move an object relative to it's angle?
if i try to move it along the x axis, it doesn't move in the direction ITS x axis is pointing (red arrow on picture)

polar acorn
#

It does

polar acorn
#

Are you moving the ship without moving the hitbox

#

Are you moving the Player object or the Hitbox object

wintry quarry
eager wolf
polar acorn
#

So rotate the ship object, but move the hitbox

shell ice
#

hello

#

how can i make the spriteRenderer of my object blink whenever his health is less then a certain value

polar acorn
#

So rotate the ship object but move the hitbox

rich adder
wintry quarry
#

(color would also be how you'd tint it white, or red, or black, or whatever you want to do)

shell ice
stuck palm
#

i sorted it out its fine

wintry quarry
#

and again you don't need your fields to be on the BUtton component itself, having a separate component would work fine, but glad it's working

stuck palm
#

oh right

#

okay

hallow totem
#

I think I have both of these here, no?
public void TakeDamage (int damageAmount)

keen dew
#

The problem is on the previous line. Probably a missing semicolon

hallow totem
#
{
    public int HP = 100;
    public GameObject;
    public void TakeDamage (int damageAmount)
    {
        HP -= damageAmount;
        
        if (HP <= 0)
        {
            PlayerDead();
        }
        
    }```
If I add one I get this instead.
wintry quarry
#

This is not a valid line of code

#

This variable is missing a name

#

you need:
<access modifier> <type> <name>

#

You have:
<access modifier> <type>

hallow totem
#

Oh yeah I meant to delete it, my bad, thanks.

#

Um... Looks like Unity is still in safe mode after relaunching the project even though there aren't any errors, how can I get it back into the regural mode?

wintry quarry
#

just looks like your console window is maximized

keen dew
#

Press shift+space

wintry quarry
#

Or double click on the title of the Console tab

#

Or right click it and press Maximize or Restore or whatever

hallow totem
#
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class Player : MonoBehaviour
{
    public int HP = 100;
    public void TakeDamage (int damageAmount)
    {
        HP -= damageAmount;
        
        if (HP <= 0)
        {
            PlayerDead();
            print ("is dead");
        }
        
    }
    private void OnTriggerEntry(Collider other)
    {
    if(other.CompareTag("ZombieHand"))
        {
            TakeDamage(100);        
        }
    }
    private void PlayerDead()
    {
        GetComponent<MouseMovement>().enabled = false;
        GetComponent<PlayerMovement>().enabled = false;
    }
}```
So I'm not getting any errors but my HP is not decreasing nor am I losing the ability to move even if I lower it through the inspector.
#

The tags look right, the object that's tagged has a colider and so does the player.

eager wolf
#

the code in red doesn't stop the coroutine, why is that?

short hazel
#

That's not how you stop a coroutine, in fact your code starts a new one and promptly stops it

#

StartCoroutine() returns a value, you need to store that in a variable and pass that variable to StopCoroutine()

#

ie.

Coroutine co = StartCoroutine(AnimationAAA());
// later...
StopCoroutine(co);
#

Your coroutine methods are also nested in another method, you might need to take them out if you get errors like "Coroutine xyz could not be started"

hallow totem
#

Eh... Thanks, happens way too much, wish they supported VScodium and half of these issues could've been avoided. :'3

wintry quarry
#

Use Visual Studio or Rider and you'll get autocomplete for those MonoBehaviour message methods

keen dew
#

You can't get further help here unless you use a configured IDE

hallow totem
#

Yeah I probably should, just to not spam this channel so much, even though I don't plan on using unity much longer.

topaz hull
#

Hey so I have a "world border" that I want to follow the player as the player moves upwards., but I don't want it to follow it downwards

#

Is there a command that only adds the players positive y-axis movement to the object?

polar acorn
#

Check if the player is above the object. If it is, increase height to match.
This doesn't do anything if the player is below the object, so it won't move down

topaz hull
#

Yeah but the border is always gonna be below the player

#

It's a kind of trigger that "kills" the player if the players leaves the screen

#

I suppose I could link it to another object using that method

hexed terrace
#

if playerYvelocity > 0.1 { move border }

topaz hull
#

And then how would I make the border move up?

#

Like what line of code does that

#

It's transform right?

hexed terrace
#

google -> unity how to move object

topaz hull
#

Yeah but does that move it at the same speed as the player?

hexed terrace
#

it moves it at the speed you tell it to move at..

topaz hull
#

Cuz the player is jumping so it's exponential

polar acorn
#

If the player is closer than that amount, nothing changes

topaz hull
#

Yep, gonna have to google how to do that

rare basin
#

I am confused with a how to convert rotation on the Z axis on float from (-1;1) based on the rotation on the Z axis. So I am making a steering wheel, when starting the game, the mappedValue should be 0, when the steering wheel is turned left by the maximumDegrees the mappedValue should be -1, and when turned right by the maximumDegrees, it should be 1 and smoothly interpolate, so when turned halfway it should be 0.5f etc... Althought this code doesn't work, and work differently under a child etc, what am I missing to make this work

#
public class SteeringWheelMapper : MonoBehaviour
{
    public float mappedValue;
    public Transform steeringWheelTransform;
    public float maximumAngle = 90;

    public void MapRotationToValue()
    {
        float rotationZ = steeringWheelTransform.localEulerAngles.z;

        if (rotationZ > 180)
        {
            rotationZ -= 360;
        }

        mappedValue = rotationZ / maximumAngle;
    }

    private void Update()
    {
        MapRotationToValue();
    }
}
flint python
#

Does anyone know or link to documentation that has code example of how composition works? All I found was explanation but no examples of how several scripts works together and how you use the same script for several object, like stat script for player and enemy

vernal crow
#

What did I do wrong

polar acorn
#

Instead of having one script that's like "Player", you have a dozen scripts for things like "Damageable", "Controllable", etc.

polar acorn
vernal crow
#

But fr tho what did I do incorrectly

languid spire
hexed terrace
vernal crow
#

I’m trying to get it to load the next level on collision of an object

polar acorn
normal coyote
#

Can someon help me? im making a 2d game for a college project, and i made a build of my game some time ago, and the scenes were changing as it should. But, when im playing the game in the "game" window of unity the scenes doesn't change, is it normal? Do i need to change some configuration?

(srry for the bad english, it is not my native language and im really tired lol)

wintry quarry
vernal crow
polar acorn
vernal crow
hexed terrace
#

you shouldn't been screenshotting !code anyway 👇

eternal falconBOT
hexed terrace
languid spire
eternal needle
# rare basin ```cs public class SteeringWheelMapper : MonoBehaviour { public float mapped...

It could be an issue that you're reading the euler angles. It could occasionally use different euler angles which result in the same rotation as the one you expect. To solve this you would need to keep track of your own euler values
Although I dont really see either where you try to map it from -1 to 1. Diving by 90 would mean that at most the value is -90 or 90 but this clearly wouldnt always be true

vernal crow
slender nymph
rare basin
#

and pass it to the vehicle controller to use that instead

#

So you can turn the steering wheel by 180 degrees left (-1 value) and 180 degress right (1 value). I need to calculate that value based on the rotation on the Z axis and I find it really confusing

hexed terrace
#

what values does the steering wheel spit out when you turn it?

rare basin
#

it depends, that what drives me crazy

#

what values are you asking about?

#

the mappedValue or localEulerAngles.z?

#

it works correctly when the steering wheel is not child of any transform

#

but when i put it under the car parent, the values are broken

wintry quarry
#

you should maintain your own float variable for the rotation

rare basin
#

that's what I thought but I am not sure how can i maintain my own float

hexed terrace
rare basin
#

no sorry, my bad i phrased it wrongly

#

it's a steering wheel you can grab via VR controllers in game

#

and rotate it using your hands(Controllers)

#

all i want to do is to map the rotation on the Z axis to a float :/

wintry quarry
#

Well ok actually if you want to read back the angle from the wheel itself you can use Vector3.SignedAngle(wheelHolder.up, steeringWheel.up, wheelHolder.forward) where wheelHolder is a Transform that is oriented such that it's at the "resting/neutral" position/rotation of the steering wheel if that makes sense

#

also a child of the car like the wheel itself is

rare basin
#

wheel is the steering wheel right

#

not the actuall vehicle wheel

wintry quarry
#

yeah sorry

rare basin
#

so i can make some kind of parent of the steering wheel

#

like Steering Pivot

wintry quarry
#

yeah

rare basin
#

that gizmo is from Steering Pivot

wintry quarry
#

yeah exactly and basically

rare basin
#

and Steering Wheel at 0,0,0?

wintry quarry
#

if you can imagine measuring the angle between the green arrow of this thing and the geen arrow of the wheel AROUND the blue arrow

#

that's what SignedAngle will do

rare basin
#

alright let me try that

#

makes sense

#
    public void MapRotationToValue()
    {
        float angle = Vector3.SignedAngle(wheelHolderTransform.up, transform.up, wheelHolderTransform.forward);
        mappedValue = angle / maximumAngle;
    }

    private void Update()
    {
        MapRotationToValue();
    }
#

so somethnig like that

#

where my maximumAngle is 180

#

well yea this works

#

now, how could i clamp the rotation kinda

#

clamping the mappedValue is easy enough

#

but how can i prevent the rotation (eulerAngles??) to go above my maximumAngle

#

if that makes sens?

#

like so you cannot turn the steering wheel anymore in that direction if it reached the maximumAngle, or mappedValue (-1, 1)

#

another thing I cannot understand that, somehows my rotation on X and Y axis still happens

#

when im holding the steering wheel

#

even when it's contrained in the inspector

wintry quarry
#

they don't prevent other things from rotating it

#

like the VR stuff

#

also why does the wheel need a Rigidbody anyway?

rare basin
#

so it's Grabbable

#

by the VR Hand

#

and rotatable

#

by the hand when holding it

wintry quarry
#

Is that not doable without a Rigidbody?

#

I don't know much about VR

rare basin
#

not with the asset im using

#

it's all physics based

#

the way it works is that

#

it snaps the hand to the steering wheel

#

using customizable joint

#

and that breaks the car stability aswell and a lot of stuff

#

and im trying for days now to make it work ;p

#

let me record a actuall VR gameplay to explain better what's happening

honest haven
#

Hi can i have some help please. i dont under stand why my slider vlaue is -200. So currentEXP is 400 and expToNextLevel[CharacterStats.playerLevel] is 300. ```if (CharacterStats.currentEXP > GameManager.instance.expToNextLevel[CharacterStats.playerLevel])
{
CharacterStats.currentEXP -= GameManager.instance.expToNextLevel[CharacterStats.playerLevel];

        var test = CharacterStats.currentEXP -= GameManager.instance.expToNextLevel[CharacterStats.playerLevel];
        
        CharacterStats.playerLevel++;

        expLevel.value = CharacterStats.currentEXP;
        
        expLevel.maxValue = GameManager.instance.expToNextLevel[CharacterStats.playerLevel];

        Debug.Log( test + "/" + expLevel.maxValue );
short hazel
#

The line where you create your test variable has the -= too, which means it'll subtract twice

#

Assignments can be chained ie. var a = b = c; is perfectly valid

rare basin
#

basically the car is moving by physics obviously, to make it realistic

honest haven
short hazel
#

It is, a -= b is short for a = a - b
But you did var test = (a -= b) which does a = a - b and puts a into test

rocky canyon
rare basin
#

they change in runtime to some weird values

#

not sure why, probably cuz of physics

#

and all the integrations and joints etc

rocky canyon
#

wonder why they change from 1:1:1

rare basin
#

no idea

#

probably because of the customizable joint

rare basin
#

the hand is creating with the steering wheel

rocky canyon
#

ahh yea that could be it

rare basin
#

when grabbing it

#

and as mentioned, that messes up the entire car physics etc :/

rare basin
#

yea kinda 😄

rocky canyon
#

besides the wheel going all crazy at the end.. it looks pretty good

rare basin
#

yea it does but it's not useable haha

rocky canyon
#

using localRotations?

rare basin
#

to what?

rocky canyon
#

for the wheel's rotations

#

it appears to work fine until the actual car rotates..

rare basin
#

im using a asset for VR Interactions

rocky canyon
#

makes me think ur not using transform.localRotation for the wheels rotation

rare basin
#

all the rotation is done by the hand

#

that is from external asset

#

all the grabing etc

rocky canyon
#

yea, but it has to manipulate the steering wheels rotation

rare basin
rare basin
#

everything

#

that's why the steering wheel has to be a rigidbod

#

when i set the rigidbody to kinematic, it doesnt turn at all

#

but is still grabbable

rocky canyon
#

true. but theres also local and world versions for Rigidbody functions

#

AddTorque.. vs AddLocalTorque

#

Relative Torque i mean

rare basin
#

would need to browse the asset's code

#

but it might be even deeper

#

from Unity's code

#

in the XR Integration Toolkit

rocky canyon
#

ya, but the asset may be assuming that all rigidbodies are global...

eternal needle
rare basin
#

that is the grabbable (steering wheel) component

rocky canyon
#

if u have one nested as a child object.. the asset could not be able to account for that

rare basin
#

i can use my custom grab joint but i have no clue

rocky canyon
#

ahh yea, since u have joints set up u should be able to constrain it that way

rare basin
#

holy shit that's massive haha

#

that's the DefaultJoint

#

the hand+steering wheel connection uses

eternal needle
#

How are all of them locked but still moving? Maybe theres more magic going on

#

I'd expect angular Z to be not locked, whatever the other option was.

rare basin
#

no clue

rocky canyon
#

is this joint on the wheel? or is it on the hand?

rare basin
#

checking rn

#

would take a minute because it's hard to debug stuff with your VR headset on 😄

rocky canyon
#

i think we're assuming its on the wheel. thats y he said he expects teh Z to be unlocked..

rare basin
#

it creates the joint on the hand

rocky canyon
#

im thinking thats on the hand tho.. the joint its using to attach to items u grab

rare basin
#

i grabbed the steering wheel with

rocky canyon
#

ya,

eternal needle
#

Ah I see

rare basin
#

that is the joint

#

that has been created on the hand

#

when i grabbe the wheel

rocky canyon
#

ya, its def the code from the asset. not liking the way u have ur steering wheel/ heirarchy structure

eternal needle
#

What about the rb on the wheel? What constraints do you have

rare basin
rocky canyon
#

can u show the hiearchy of this?

wintry quarry
#

Yeah problem with Rigidbody constraints is they're based on world space

rocky canyon
wintry quarry
#

So if your car can turn that's not gonna work really

eternal needle
#

Yea that's unlucky

rocky canyon
rare basin
#

so what about a workaround

#

that i unparent the steering wheel

#

and the player

#

and in the update i just move them to the proper spot

wintry quarry
#

Yes I would think something like that might be appropriate

#

Late update tho

rare basin
#

yea, let me try

wintry quarry
#

IDK it might get weird

#

Really weird

rare basin
#

let's see lol

eternal needle
#

That would be like making a physics scene wouldnt it?

rare basin
#

should I also unparent the player from the car?

wintry quarry
#

I would probably make a physics scene for inside the car 😊

rare basin
#

because it creates a joint with the wheel

#

and when the player will be a child of the car

#

the car physics might be broken

rocky canyon
#

ive done something similar.. where i kept the object a root object.. and then just used lateupdate to track it to the object it should be connected to

#

that way the rigidbody is still in world space..

rare basin
#

or shoudl i just unparent the wheel lol

rocky canyon
#

well how would that work in the long run?

#

i bet if u unparent it tho it will work as expected..

#

should atleast try it.. so you can confirm its the hiearchy

rare basin
#

Steering wheel and player unparented from the car with a script that sets their position to a proper spot in late update

#

test number one 😄

rocky canyon
#

test it... rotate it so its not facing forward anymore.. and then test again

rare basin
#

can i also safely do transform.forward = transformToFollow.forward

#

for the player

#

so the camera works in realistic way

rocky canyon
#

ya, that will sync their rotations

rare basin
#

ok my motion sickness went crazy

#

almost puked

#

it kinda works but doesnt xd

rocky canyon
#

i have respect for u vr guys..

rocky canyon
#

i couldn't develop with my head in a headset all day

rocky canyon
rare basin
#

nah its still broken

#

the steering is reversed

#

and there are very weird physics for the car

rocky canyon
#

i was gonna say too.. if u unparented it from the car.. u could keep the rigidbody as a root object.. in world space.. and just use a hinge joint to connect it to the car

rare basin
#

like collidrs under the car

#

but they arent there

#

look how the car is jumping with my head

hexed terrace
rare basin
#

kinda

#

wannabe 😄

#

any other ideas how to fix it? 😦

prime cobalt
#

Is there anything wrong with how I did this? The object I'm clicking was painted with the 2d tilemap gameobject brush if that matters at all.

#

It never prints the debug log

hexed terrace
#

IIRC IPointerClickHandler requires a collider

prime cobalt
#

I gave the gameobject a box collider

rare basin
#

do you have physics raycaster on the camera?

prime cobalt
#

I have one that looks for something totally different

#

Oh are you saying just to use that instead?

rare basin
#

just add that component

hexed terrace
prime cobalt
#

Ok it works thanks

rocky canyon
hexed terrace
#

always check the docs 😉

rare basin
#

i think it works

#

and im just dumb

#

and made some modifications to the untiy's terrain yesterday

#

and they are invisible

#

yup xd

#

thanks for the help guys and @rocky canyon especially

crude sphinx
#

Guys, why does my player fly away as soon as I add the character controller?
I'm using a rigidbody for the movement calcs, but I only want to use a character controller to check and manipulate the height of the player....

slender nymph
#

rigidbody and CC don't mix, choose one or the other

crude sphinx
#

I know, but idk how I would do my sneaking code otherwise notlikethis

public CharacterController PlayerHeight;

private void StartSneaking(InputAction.CallbackContext context)
    {
        Debug.Log("I'm sneaking");

        if (isGrounded)
        {
            PlayerHeight.height = sneakHeight;
            moveSpeed = sneakSpeed;
        }
    }
polar acorn
slender nymph
#

yeah the CC.height property just affects how tall the capsule collider is. either just swap colliders on the rigidbody or make its collider shorter

eternal needle
#

naming your CharacterController variable PlayerHeight is also really confusing

eager wolf
#

Why does this code only return 1 item in the loot table even if there are 2?

polar acorn
#

this really shouldn't be a loop

#

You should just do Item item = lootTable[0] and then run your code

noble river
#

hello guys, does any one know what the code is for dynamically adding a TextMeshProUGUI to a UI Panel via script?

polar acorn
noble river
#

Got it. Thanks

noble river
polar acorn
noble river
#

oh I see it. Thanks

eager wolf
# polar acorn You should just do `Item item = lootTable[0]` and then run your code

wait, what exactly do you mean by that? how would that look like?

Here's my current code

    List<Item> GetDroppedLoot()
    {
        int randomNumber = Random.Range(1, 101);
        List<Item> possibleLoot = new List<Item>();
        foreach (Item item in lootTable)
        {
            if (randomNumber <= item.dropChance)
            {
                possibleLoot.Add(item);
                print(item);
            }
        }
        return possibleLoot;
    }
eager wolf
#

i just fixed it :)

polar acorn
#

The code you showed returns the first thing it finds in the list

eager wolf
#

but you mentioned an optimization i don't know how to code

#

this is how the code is meant to work

#

OH

#

nvm

polar acorn
eager wolf
#

my brain just understood

#

thanks bro!

polar acorn
#

This one actually does use more than the first element so a loop makes sense

abstract finch
#
    {
        _recoilPhase = RecoilPhase.Kick; //Go To Recoil Positiion
        _currentRecoil = _recoilStrength;
        yield return new WaitForSeconds(_recoilDuration);

        _recoilPhase = RecoilPhase.Recovery; //Reset To Original Position
        _currentRecoil = -_recoilStrength;
        yield return new WaitForSeconds(_recoilDuration);
        _currentRecoil = 0;
    }```
I'm trying to create some code for a recoil function but it doesn't seem like it's going back to the original position. I don't want to hardset it using Vector3s, is there a way to somehow get it to return to it's original position? It's basically pulling the camera up for a duration then pulling it back down
open gull
solar charm
#

anyone knows why the wait function isnt... well waiting? i can shoot infinitely fast

polar acorn
#

Also you're missing a yield return

solar charm
polar acorn
#

it delays a coroutine

#

it doesn't do anything anywhere else

solar charm
#

ahhhh alright thanks

sick jay
#

hi yall:
for some reason, in editor play mode(and in a test build i just made), when i look at a particularly performance heavy section of the game, it causes my mouse sensitivity to increase by like a lot. im assuming it has something to do with the code, and that its handled in update and based on framerate of the game or something. how can i fix that in code? i want the game to be able to run on any framerate. i use cinemachine for the camera handling and this bit of code is the only other thing that uses the camera

solar charm
polar acorn
#

Where do you call StartCoroutine

solar charm
solar charm
#

OH MY GOD I AM SUCH AN IDIOT I FIXED IT THANK YOU!

coral crater
#

my character in my game has inventory slots, in a small window of rotating items ^^. each itemslot is represented in the heirarchy as an object with an itemslot monobehaviour script on, which holds serializable properties. the itemslots are held in an array in the inventorymanager. I'm trying to implement code to make the slots "shuffle" up or down when you press left/right with the inventory open, but I can't seem to crack the final implementation of making the slots actually move their values, any advice?

#

debug seems to show everything working as intended, but no values actually move

wintry quarry
#

also your code is only doing that - moving items around in the array

#

it isn't going to move the position of the objects in the game

cold orbit
#

Why does my activeBuildingType doesn't change when i click the button???

deft grail
low perch
#

!code\

eternal falconBOT
low perch
#

test

cold orbit
#

@deft grail sorry where should i add it, after activeBuildingType = buildingTypeSO; ????