#archived-code-general

1 messages Β· Page 283 of 1

glossy wave
#

problem solved! thank you so much πŸ™‚

sudden stump
#

Elder Camel System?

dreamy wave
#

probs just a simple answer but im making like a vinyl player and its as simple as making an event for each like "disc" that activates music when played ye?

glossy wave
sudden stump
#

What does ECS stand for again?

glossy wave
#

entity component system

#

what Burst-compatible ways are there to move my camera position to the position of a LocalToWorld component? I get this error (the code works but the error appears and I don't like it):

Burst error BC1016: The managed function UnityEngine.Transform.set_position(UnityEngine.Transform* this, UnityEngine.Vector3 value) is not supported

#

my camera isn't an Entity but I have stored a reference to it with code

molten timber
#

a.SetActive(false); is making my ar not show in game anybody that could help ,e

leaden ice
swift falcon
#

hey does anyone know how to convert quaternions to degrees?

#

google hasn't been really helpful

hexed pecan
swift falcon
#

oh i just need to convert transform.rotation.x to degrees

hexed pecan
#

transform.eulerAngles.x

swift falcon
#

ohhhhhhh

hexed pecan
#

Yeah transform also has eulerAngles. Same as typing transform.rotation.eulerAngles

elfin tree
#

Is there a way for a raycast to target (or ignore) multiple layers at one?

hexed pecan
elfin tree
#

ah thanks!

swift falcon
hexed pecan
#

I like to use Mathf.DeltaAngle(0f, angle) to convert an angle into -180...180 range

molten timber
swift falcon
#

ohhhhhh thanks

molten timber
#

should i make it true_

hexed pecan
#

It gives the fastest angle from the first parameter which is 0 in this case

hexed pecan
swift falcon
#

5 but im inverting it

hexed pecan
#

Oh nvm that's -355 so 5 yeah

swift falcon
#

it works perfectly, thanks

#

however um do you happen to know why my stuff tend to clip through things at times?

#

like if i go 25+km at a wall or the floor it will phase through?

hexed pecan
#

Do you have a rigidbody and how are you moving your objects?

swift falcon
hexed pecan
#

2D or 3D?

swift falcon
#

vector3

hexed pecan
#

So it's Rigidbody and not Rigidbody2D?

swift falcon
#

yup

hexed pecan
#

Should try using velocity or AddForce instead to move it

swift falcon
#

but it still happens even when i let stuff fall with gravity

hexed pecan
#

MovePosition doesn't really give accurate collision AFAIK

swift falcon
#

i made a drone and when it falls out of the sky half of the time it phases through the ground plane

hexed pecan
#

Don't move it with MovePosition πŸ€·β€β™‚οΈ

swift falcon
#

ill give velocity a try

hexed pecan
#

You need to keep your previous rb.velocity.y if you don't want to override the gravity

elfin tree
#

Am I missing something? (output in image)

    if (_groups[group].Count < currentIndex + 1) return null;

    Debug.Log("count: " + _groups[group].Count);
    Debug.Log("index: " + currentIndex);
    
    return _groups[group][currentIndex + 1];
swift falcon
rain minnow
soft shard
# swift falcon movePosition is so goofy

AFAIK MovePosition and MoveRotation are designed for Kinematic rigidbodies, where Unity assumes youll handle physics yourself, but when using velocity or AddForce, then Unity handles the physics for you, and its best to use these things in FixedUpdate as thats the rate Unity will check for physics collisions - if the object is moving really fast (for example like a bullet), you could also interpolate the movement, which will try to predict collision a frame ahead of the velocity

swift falcon
#

yeah they are all in fixedupdate but it still happens

#

ill try the other two later

#

i mean i'll probably change the system entirely

#

but thanks for your input

thick terrace
#

did that HDRPPACKAGE_EXIST symbol get added to your player settings maybe? you might need to manually remove it

versed spade
#

I followed this video on how to get 0-G traversal for a spaceship working in which he used UnityEngine.Input to map controls. My issue is that these are based on the X and Y axis which works for WASD in that system. How would I get this working for Input system? Guides aren't clear.

        float yAxis = Input.GetAxis("Vertical");
        float xAxis = Input.GetAxis("Horizontal");

        ThrustForward(yAxis);
        Rotate(transform, xAxis * -rotationSpeed);```
#

Trying Copilot for some code advise. It tried getting me to put WASD and the LeftStick controls under one Action in my Action Map, but that still wouldn't give me the X and Y

#
    private void ThrustForward(float amount)
    {
        Vector2 force = transform.up * amount;

        rb.AddForce(force);
    }

    private void Rotate(Transform t, float amount)
    {
        t.Rotate(0, 0, amount);
    }```
the two called functions are like this. The Axi aren't called in the below code. Edit: No its just a 0 -1 or 1 pretty much. 0 means no press and no force to be added, 1 means positive force, and -1 means negitive force
primal wind
#

You can get the value of an Action provided it has the correct type with InputAction.ReadValue

#

Assuming your action is a Vector2, you can do yourInputAction.ReadValue<Vector2>()

versed spade
#

And it will know that WS is Y and AD is X?

#

My confusion comes from this:
float yAxis = moveAction.ReadValue<Vector2>().y
How would it know WS are y values.

primal wind
#

When you set up a vector 2 input action in the editor, it has a Up Down Left Right component. Up/Down is Y and Left/Right is X

#

If you created it through code, you just have to bind it correctly

versed spade
#

Do you bind it in the Action editor or through code

primal wind
#

If you have an InputAction asset, do it through the editor. If you created one in code only, you do that there

versed spade
#

So like this?

thin hollow
#

On my player character I've made a lot of variables to have [SerializedField][ReadOnly][Foldout("Debug states")] attributes ("Read only" and "Foldout" are attributes from Naughty Attributes addon), to monitor their values and see how my logic behaves. I've noticed that whenever I select my player object during playmode, the performance starts to lag quite noticeably.
I guess that's because I have too many serialized fields on a display in the Inspector so it struggles with updating them every frame, but if it so, are there any other ways I could monitor state of a lot of variables at once in realtime in Unity editor? I have a comparable amount of debug-exposed variables on my NPC scripts as well, so I suspect it would cause the editor to lag as well, though I didn't test that yet.

rain minnow
thin hollow
# rain minnow It's editor lag. Do you need to constantly check so many fields at once? Have y...

I thought I would waste too much time coding that ugui versus simply sticking [serializeField] on a variable, and I'd need to update it each time I add a variable to the "watch list".
I don't know if I need to watch so many variables, but when I'm playtesting my player controller, or NPC, and suddenly things don't work as they should, I want to inspect what exactly is the state of the object to understand what caused it to go wrong, since most often the issue is not a code error, but in logic flow. Can't do that with a regular break points in code since those issues are situation-specific and involve code that executes pretty much every frame or every fixed update, so any break point would be triggering constantly, making game unplayable.

cosmic rain
thin hollow
cosmic rain
#

You can profile the editor

heady iris
#

It can also be unreliable

#

I've seen cases where the play loop was allegedly taking only 3ms (it's more like 10)

#

i think a bunch of stuff was getting stuffed into EditorLoop

static matrix
#

I have a very fast moving object and its rigidbody is not colliding even though I set the collision to contiguous any idea why?

cosmic rain
static matrix
#

continuous dynamic

cosmic rain
#

Does it also rotate? Does the other colliding object move or rotate as well?

static matrix
#

it does not rotate, and the other objects are static

#

maybe its just too fast

steep herald
#

@static matrix static in the sense that they do not have a rigidbody?

static matrix
#

static as in the sense that they do not move
they technically also do not have a rigidbody

steep herald
#

@static matrix what is the collider type on the dynamic object

cosmic rain
#

Also, how are you moving it?

icy depot
#

How does Debug.Log take virtually any parameters without the user ever needing to use <T> jargon?

rain minnow
# thin hollow I thought I would waste too much time coding that ugui versus simply sticking [s...

True, but there will be some inconvenience with either method. Most people will have an in-game console or debugger to do that, especially since running in the editor with the inspector will slow down the game

You can test this. Maximize the screen during runtime. The game will run smoother than in window mode with the editor visible

I'd remove variables that you've already tested or group them into smaller foldouts to avoid a heaping list of variables . . .

cosmic rain
rain minnow
#

There is no need for generics . . .

icy depot
#

wait.. so you can make Object be a parameter type... what... woah...

#

that's mindblowing

rain minnow
icy depot
rain minnow
#

@icy depot Note the difference between object and Object . . .

cosmic rain
#

You can have a void* as a parameter in C++. Now that's mind blowing... The first time you hear about it.

icy depot
#

you... can...?

cosmic rain
#

Yeah. There's a lot of stuff you can in programming.

icy depot
cosmic rain
#

object is an alias to System.Object afaik.

icy depot
#

oh wait so object is a type name just as lowercase float and int are?

rain minnow
static matrix
#

ah yes mister . . .

icy depot
#

so System.Int's the official int name?

#

or

#

System.Int32

rain minnow
icy depot
#

oh!

cosmic rain
icy depot
#

oh...

#

then, does void also have an official name?

#

also how do you do the spaced dots?

#

oh wait

#

. . .

cosmic rain
cosmic rain
icy depot
#

oh.. so void's just syntax

thick terrace
#

System.Void is a type

rain minnow
#

I just didn't write their fully qualifying names . . .

thin hollow
rain minnow
versed spade
#

I need to get the 0, -1, and 1 values from ThrustControl > Vertical || Horizontal in my code. How do I call the Composite Behavior in code?

leaden ice
versed spade
#

1D axis according to the Composite Type

leaden ice
#

sure but why

versed spade
#

Why what?

leaden ice
#

Why have two different 1D axis for horizontal/vertical

#

instead of a 2d axis?

#

What are you trying to do here exactly?

versed spade
#
    private void Update()
    {
        float yAxis = playerControls["Vertical"].ReadValue<float>();
        float xAxis = playerControls["Horizontal"].ReadValue<float>();

        ThrustForward(yAxis);
        Rotate(transform, xAxis * -rotationSpeed);

        //Store ship data for UI
        currentVelocity = rb.velocity.magnitude;
        currentHeading = rb.rotation;
         
    }```
I am trying to modify some code I made for Zero G traversiel in which I need to call a value to find whether the user is giving a positive or negitive Y and positive and negitive X to trigger my players rotation and Thrust
leaden ice
#

Select the ThrustControl axis and set it to:
Action Type: Value
Control Type: Vector2

Remove your existing bindings
Make a single binding of type "up/left/right/down composite", and bind all four buttons to it

versed spade
#

Sorry fairely new to Input System

leaden ice
#

Yes I know that and I'm helping you

versed spade
#

I Thank you for that πŸ˜„

leaden ice
#

then in your code you will do cs Vector2 thrustInput = playerControls["ThrustControl"].ReadValue<Vector2>();

#

you can then do whatever you want with that - including reading thrustInput.x and thrustInput.y

versed spade
leaden ice
#

yes

hallow current
#

can some 1 help me whit fixing a script

versed spade
hallow current
#

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

public class Slot : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public bool hoverd;
public Item heldItem;

private Color opaque = new Color(1, 1, 1, 1);
private Color transparent = new Color(1, 1, 1, 0);

private Image this slotImage;

public void inistialiseSlot()
{
    thisSlotImage = gameObject.GetComponent<Image>();
    thisSlotImage.sprite = null;
    thisSlotImage.color = transparent;
    setItem(null);
}

public void setItem(Item item)
{
    heldItem = item;

    if (item != null)
    {
        thisSlotImage.sprite = heldItem.icon;
        thisSlotImage.color = opaque;
    }
    else
    {
        thisSlotImage.sprite = null;
        thisSlotImage.color = transparent;
    }
}

public Item getItem()
{
    return heldItem;
}

public void OnPointerEnter(PointerEventData pointerEventData)
{
    hoverd = true;
}

public void OnPointerExit(PointerEventData pointerEventData)
{
    hoverd = false;
}

}

#

idk whats wrong whit it

versed spade
#

btw you can put code in a codeblock with three `

hallow current
#

what?

vagrant blade
tawny elkBOT
versed spade
#

Thx

icy depot
#

I'm looking to check if a coroutine is running. On the internet, I found that you could just be straightforward and make a bool for each coroutine. Is there a more efficient, or should I say, cleaner way to know if a coroutine is running or not?

vagrant blade
icy depot
#

And, what would happen if I tried running a coroutine that's already running>?

vagrant blade
#

If your IDE isn't underlning things. You need to configure it !ide @hallow current

tawny elkBOT
vapid condor
icy depot
#

so.. two instances will be alive?

vapid condor
#

yeah

icy depot
#

that would suck...

vapid condor
#

if you do a start couritine during update it will start a new courutine every frame

#

which is something you would want to avoid

rain minnow
icy depot
#

wait, so null means it's running or not? that works?

#

I had that in my code originally but it was just intuition

#

so why isn't it the first result when I look the matter up? weird..

rain minnow
#

You'd assign null to the coroutine variable at the end of the coroutine method (indicating its finished) . . .

icy depot
#

ohhhhh!

#

time to go do that

#

wait.. while it's running? that works? well i suppose..

#

coroutines are weird...

spring creek
#

So it doesn't matter what you assign to it, it won't affect the coroutine

vapid condor
#

@icy depot i made an utility function that can be used to be able to have courutines start in update without creating new instances per frame

/// <summary>
/// Execute logic once
/// </summary>
/// <param name="logic">The logic to execute</param>
/// <param name="wasExecuted">Set the referenced bool to false to execute again</param>
public static void DoOnce(Action logic, ref bool wasExecuted)
{            
    if (!wasExecuted)
    {
        wasExecuted = true;
        logic.Invoke();
    }
}
rain minnow
icy depot
#

volt, that's amazing

#

wait, what's Action?

#

and Invoke.. new terms...

vapid condor
#

basically a void function as a parameter

little meadow
swift falcon
#

In layman's terms its a function to call other functions

#

When you Invoke a Action / Func the functions that were subscribed to it get called

vapid condor
#

you use it like this

DoOnce(() => { /*your logic here*/ }, ref yourBool);
icy depot
#

that's some funny syntax that i've never worked with

#

so you can call a whole function in a function

vapid condor
#

they are called lambdas

swift falcon
#

That's a lambda expression not the same as a Action

icy depot
#

what exactly does => do in a broader scope?

vapid condor
swift falcon
#

So you know how Methods have parameters maple?

icy depot
#

yep!

#

wait

#

so () is the parameters!

#

right..?

swift falcon
#

The () is the method parameters in the sense and the => is the body of the function

#

You got it!

vapid condor
icy depot
vapid condor
#

the => basically declares the body

icy depot
#

if there was a parameter or two, how'd it look?

versed spade
# leaden ice then in your code you will do ```cs Vector2 thrustInput = playerControls["Thrust...

Keep getting a Null ReferenceExpection: Object reference not set to an instance of an object
I called thrustControl as public Vector2 thrustInput; but it seems to still error.

    private InputActionMap playerControls;
    public Vector2 thrustInput;


    #region Monobehaviour API

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        thrustInput = playerControls["thrustControl"].ReadValue<Vector2>();
    }
swift falcon
#

(Parameters) => { function body}

#

(Paramater 1, parameter 2)

icy depot
#

oh and I don't get the ref keyword..

vapid condor
icy depot
#

so the type is also in!

vapid condor
icy depot
#

ohhhh

#

so as if it were a class

#

or struct

vapid condor
#

basically when you give it a variable that variable can be modified inside the function

icy depot
#

ohhhh

vapid condor
#

ref is the equivalent of & in c++

#

its a pointer under the hood

leaden ice
#

wasn't it capitalized in your action asset? ( and my example )

versed spade
#

It was, changed that just now but its still struggling

leaden ice
#

"still struggling" how?

#

What errors are you seeing? What problems?

versed spade
#

    private InputActionMap playerControls;
    private Vector2 thrustInput;


    #region Monobehaviour API

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        thrustInput = playerControls["ThrustControl"].ReadValue<Vector2>();
    }

    private void Update()
    {
        float yAxis = thrustInput.y;
        float xAxis = thrustInput.x;

        ThrustForward(yAxis);
        Rotate(transform, xAxis * -rotationSpeed);

        //Store ship data for UI
        currentVelocity = rb.velocity.magnitude;
        currentHeading = rb.rotation;
         
    }

Its giving me NullReferenceException: Object reference not set to an instance of an object AdvancedPlayerMovement.Start () (at Assets/Player Logic/AdvancedPlayerMovement.cs:26)

leaden ice
#

Did you ever assign playerControls anywhere? From your snippet it doesn't seem like it

#

Yeah you never assigned playerControls anywhere

versed spade
#

Oh wait maybe not

#

one sec woops

#

playerControls = new InputActionMap("Player");
Is this not accurate?

#

The Action map is called Player

vapid condor
versed spade
#

Sounded off to me aswell, but its the only layer of code I found that is trying to save an action map

vapid condor
#

the input system generates an input master script that contains all your bindings, thats probably what you want to get

versed spade
#

I just don't know what method will fetch them

vapid condor
#

you basically want to do this

#

inside a manager class or something

#

then you can just call the INPUT variable and it contains a reference to all your maps and actions

halcyon shard
#

hello i have a question is unity c# version don't have the memory<T> sturct?

halcyon shard
#

i don't see the struct

leaden ice
#

Then i guess it's not there

leaden ice
leaden ice
swift falcon
#

Zane if ur using PlayerInput on ur gameobject at this point it might just be easier to use the Unity Events option on PlayerInput

leaden ice
#

they don't seem to be using PlayerInput

heady iris
#

If you want to access all of your input actions through code, turn on "Generate C# Class" on your InputActionAsset. This will create a class containing all of the action maps (which, in turn, contain all of the actions).

#

The class will have the same name as your InputActionAsset.

trail wraith
#

how would one go about assigning an audioclip to a static AudioClip field?

heady iris
#

you can't serialize static fields.

#

A reasonble alternative is to have a singleton that holds references to things.

trail wraith
#

that's the only way i can think of

heady iris
#

I tend to do this when I want to have global access to objects

trail wraith
#

in my case i have several instances of a script that are going to use the same audioclip... i suppose a singleton is the right way to do it

heady iris
#
[CreateAssetMenu]
public class GameSounds : SingletonSO<Gamesounds> {
  public AudioClip someClip;
}
west nova
#

Hi guys does anyone know what is the best way to do something like when my player goes to the next scene, and wants to go back, he lands back at the position of where he came from? I think I found a tutorial about it but I'm not sure what approach I should go for such as player prefs, scriptable objs and so on

heady iris
#

I create a single instance of this in Assets/Resources/SingletonSO and name it GameSounds

#

Now I can access GameSounds.Instance.someClip from anywhere. The asset is loaded from Resources when I first need it.

trail wraith
#

yeah that seems like a good solution

#

thanks!

heady iris
#

I do something similar for a SingletonPrefab class

#

it instantiates a prefab when I first ask for it

trail wraith
#

what does your SingletonSO class look like?

fervent furnace
heady iris
trail wraith
#

ooooooh crap

#

thanks!

west nova
heady iris
west nova
#

I keep seeing YouTube tutorials telling me to use player prefs and so on but now I'm quite confused

spring creek
#

You should just use DontDestroyOnLoad

west nova
#

Player pref is not good right? I heard it's not safe too

spring creek
#

PlayerPrefs is not great in general. It is safe.
But the issue here is reading and writing to and from the disk just for scene change data

west nova
#

So when I do something like Scene manager.load scene then I do don't destroyonload?

#

I see I see

heady iris
#

PlayerPrefs jams all of its data into the windows registry

#

so writing lots of data will annoy your users

spring creek
heady iris
#

and yes, there's no reason to use it if you aren't trying to save data between play sessions

west nova
#

Hmm but let's say now I have multiple manager .load scene scripts, I have to do dontdestroyonload for all of em ?

#

I actually do want to save data at the same time, I also want the player to spawn at the position from the previous level they came from

fervent furnace
#

eg if you go to map A to B to C to D
you push the values to stack posA, posB, posC, posD
when you go back, pop back the value posD, posC, posB, posA, though i think using stack is overkill, you probably wont stack a lots of scene

west nova
#

Ah damn thanks for the tips @fervent furnace @heady iris

#

I'm still quite confuse but thanks for telling me

heady iris
#

A stack is a perfect choice if your scenes form a tree

#

A -> B and C
B -> D and E
C -> F and G

#

You can't go in a circle

west nova
#

How do I do that? Do you have any tutorial videos link?

heady iris
#

do what?

west nova
#

How do I write the code

heady iris
#

yes, but to do what?

west nova
#

All I did during my college years till now was just load scene.blah blah blah

#

My approach to this was just making multiple scripts for every level

swift falcon
#

Yikes...

west nova
#

Sounds bad right

swift falcon
#

That would become complicated so fast

west nova
#

Ouch

#

That's what I actually did for loading my scenes

swift falcon
#

I could understand maybe a scriptable object for each scene but not entire code files

west nova
west nova
hasty canopy
west nova
#

https://youtu.be/UDY0edZZSdo?si=K3x-f-wRUdtEWikb
There's this one video which is exactly what I'm looking for, but should I follow this as I still want to keep my player health and stats when to the next level

Have you been struggling to find a nice way to share some data between your Unity scenes? Using Scriptable Objects, you can have data persist between scene changes. But, there are a few important things to take into account, so stick around until the end.

Note: This isn't a replacement for saving data to a file. This data will only survive in m...

β–Ά Play video
spring creek
west nova
#

Just when changing scenes, the player spawns at where the user wants to , of course this video doesn't include saving player stats and all that

swift falcon
#

Saving and Loading systems are quite complex in general

hasty canopy
west nova
#

What is ddol?

swift falcon
#

Don't destroy on load like they said earlier

#

Same thing

west nova
swift falcon
#

In all fairness you could use PlayerPrefs like you said

#

But that would be super botched

spring creek
hasty canopy
#

Not to mention scriptable objects will just reset to values set during build when you close the game

spring creek
#

Those managers could just live in their own scene

hasty canopy
#

So you're technically not "saving" anything in grand scheme of things

west nova
#

Alright thanks guys I shall start my journey on ddol and additive scene loading from now on

heady iris
#

when all references to the object are lost, it gets thrown out during a scene change (or when unused assets are unloaded for any other reason)

hasty canopy
versed spade
heady iris
hasty canopy
#

Lmao

heady iris
#

PlayerInput is a component that lets you run methods when input actions are performed/cancelled

#

So when the "Fire" action is performed, your method runs

#

You don't care how the "Fire" action actually got triggered. You just respond to it being performed.

swift falcon
#

Yeah lol and u can't seem to get the syntax for it down hence why I suggested just using the Unith Events

heady iris
#

...unless your actions are all things like "E Key" and "F Key", of course, which would completely miss the point of the entire input system

swift falcon
#

Also Keymapping is never fun to implement if u plan on making a relatively small game I would say it's not even worth it. (NOT TRYING TO DISCOURAGE YOU FROM LEARNING THO)

heady iris
#

I need to look into that

glossy wave
#

I'm trying to spawn a bullet (an Entity with a Physics Body in it), but it spawns into 0,0,0 instead of my player's gun position. (And the bullet doesn't fall with gravity.) Prior to installing Unity Physics (version 1.0.16) and adding the Physics Body component to the bullet prefab, the bullet was spawned correctly into the player's gun position. Why is this?

half anvil
#

I jus started unity im confused when i change the scale of an object it doesnt change a green out line apears this never happend before in my previous attempts in learning unity

half anvil
#

Didnt code anything yet

#

I legit am on step one of learning

mellow sigil
#

this is a code channel

half anvil
#

Oh damn

#

Mb

glossy wave
#

use this

half anvil
#

Alr

keen idol
#

So what is the solution for "Prefab Instance problem" Missing with GUID. I removed the prefabs from the project since I didnt need them anymore, but I get those errors on build.

leaden ice
keen idol
#

@leaden ice Oh that could be it

glossy wave
#

these are the packages in my project:

hard viper
hard viper
#

I'm confused why you are caling set component

#

also does this thing have a rigidbody?

keen idol
#

@leaden ice Ty that worked, Didnt think of that.

glossy wave
hard viper
#

i'm so confused as to what you are doing

glossy wave
#

using entity component system to instantiate bullets

hard viper
#

are you not working with gameobjects?

glossy wave
#

no, i'm working with entities

leaden ice
#

Yeah this is definitely ECS code

hard viper
#

ok, that's why none of this looks familiar to me

leaden ice
# glossy wave

Aren't you passing in the wrong thing to the Localtransform?

hard viper
#

it is strange that he would be using the more advanced ECS, but using the more primitive input system

leaden ice
#

If you want it at the parent position you would just use 0, 0, 0 right?

#

But you're passing in a world space position

#

LocalToWorld.valueRO.Position is the thing's world space position IIRC

glossy wave
leaden ice
#

sure but you are taking hte position of the LocalToWorld

#

which is a world space pos

#

I believe you want Position = float3.zero;

glossy wave
leaden ice
#

yes and you want it at the same position as the muzzle right?

leaden ice
spring creek
leaden ice
#

well I guess nvm you're not actually spawning it as a child right?

glossy wave
#

it spawned in the correct position before installing the physics addon. suddenly started appearing at 0,0,0 worldspace after installing

leaden ice
#

Ok then it's probably the physics body doing it yeah

#

you probably need to set the position of the physics body as well

hard viper
#

how big of a deal is it to update the unity editor version of a project? I’ve stayed to the same editor version for almost a year now, but changing to a windows system led to daily crashes for no reason

latent latch
#

depends if you want updates?

leaden ice
#

It's almost always just a few button clicks and some waiting, and sometimes some more manual package updates

hard viper
#

i mean how many things tend to break when updating?

leaden ice
#

occasionally there's some major incompatibility, and the risk of that gets higher the more versions you're jumping ahead

leaden ice
hard viper
#

welp, wish me luck then lmao

latent latch
#

most of what I've been waiting for still prototyping so im still using 2021/2022 stable versions

leaden ice
#

anyway just make a backup / VCS commit

#

then do it

#

and you can always roll back if it goes sideways

hard viper
#

i did a commit, and separate ZIP file in case

leaden ice
#

then don't even think twice

latent latch
#

2021 also objectively has the best project load screen currently

leaden ice
#

Also make sure after you upgrade you immediately make another commit

#

I always have commits that are just "Upgraded to Unity XXXX.XXfXX"

latent latch
#

id make another branch too

#

just for the sake of doing it

hard viper
#

it is done

#

and everything looks fine

#

i don’t trust the whole runtime fee thing, so 2022.3.20f1 is the last version for me, I suppose

versed spade
hasty canopy
hallow current
#

Do any 1 know how i can code a inventory system i have a big problem whit that

hasty canopy
versed spade
hallow current
#

it dosent work thats why im asking here

hasty canopy
versed spade
#

Oh wait inspector Generate C# class?

hasty canopy
leaden ice
leaden ice
versed spade
#
 playerControls = new PlayerInputs();
        thrustInput = playerControls["ThrustControl"].ReadValue<Vector2>();

Is the thrust Input meant to change somehow

#

Cause it can't index to playerinputs

#

is it PlayerInputs.thrustcontrol?

#

oh I got it

hallow current
#

how can i make so i can sprint?

#

!code

tawny elkBOT
versed spade
hallow current
#

i have a moving script but dont know what i need to do so i cna sprint when i hold shift

rigid island
#

sprinting = Input.GetKey(Keycode.LeftShift)

#

movespeed = sprinting ? regMoveSpeed : sprintspeed;

hallow current
versed spade
#

I would recommend you search youtube for a video regarding exactly that. Search for "How to make a player sprint in unity" and "How to use Input System" get an understanding of the basics of those and ask questions of that.

rigid island
versed spade
#

Not to be rude, but the way you are asking seems like you are struggling with the basics of this topic. Which I'd highly recommend you watch videos covering those basics first. Like videos on Unity Velocity, Inputs, etc. Then ask us in #πŸ’»β”ƒcode-beginner about anything that confused you there. But take time watching it

Talking from experience

hallow current
versed spade
#

!IDE

tawny elkBOT
leaden ice
versed spade
#

Its not going to run without the logic there for it.

hallow current
versed spade
# hallow current thats why im asking i need help you know

I understand that. I'd recommend going on youtube and getting some coverage. Honestly I would recommend you watch some videos on Unity Input System, a video on Velocities, and work from there.

Not to be rude but looking at the code it feels very shoved together. Like you are making boolean variables for your if statements and then halfware down you forgot about them and put the getkey right into the if statement.

I'd advice firstly moving to Input System with your inputs and making a function for each of your actions.

hollow escarp
#

anyone know a fix?

leaden ice
#

this is a standard NullReferenceException, which is the most common error you will receive in C#

#

you simply need to identify which thing you tried to access was null, and fix that

#

either by making it not null before you access it, or by checking if it's null before trying to access it.

rigid island
#

also dont crosspost

hollow escarp
leaden ice
hollow escarp
#

okay thanks

leaden ice
#

such as attaching the debugger, or simply Log statements

normal sail
#

anyone who got a parkour controller?

rigid island
normal sail
#

searched but cant find almost nothing,every tutorial doesnt explain a thing and its just a short resumary of what he did

#

found some sketchy things to download that is supposed to be one but its too off

rigid island
#

i almost cringe when i hear "I cant find anything" on google

quaint rock
#

its a complex thing that how its implemented heavily depends on how you game works and how your world is constructed

#

best to break it down into smaller steps

#

work on one part of it at a time

normal sail
#

3 hours tutorials 😒 im not doing this

rigid island
#

then gamedev is not for you

normal sail
#

fr

#

bro 10/11 words he talks about how he made his game,it got nothing to do with the controller πŸ’€

half anvil
#

Alr im confused

#

My code aint workin

#

Idk why

leaden ice
#

That's very unfortunate

versed spade
# leaden ice you got it πŸ‘
    PlayerInputs playerControls;
    private Vector2 thrustInput;


    #region Monobehaviour API

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();

        playerControls = new PlayerInputs();
        thrustInput = playerControls.Player.ThrustControl.ReadValue<Vector2>();
    }

    private void Update()
    {
        float yAxis = thrustInput.y;
        float xAxis = thrustInput.x;
        Debug.Log(xAxis + yAxis);

        ThrustForward(yAxis);
        Rotate(transform, xAxis * -rotationSpeed);

        //Store ship data for UI
        currentVelocity = rb.velocity.magnitude;
        currentHeading = rb.rotation;
         
    }

Gotta ask, it seems my y and x Axis are returning 0s no matter what I press. Would this be a setup issue with the action or the location of the readValue thing? Can't seem to figure it out.

half anvil
leaden ice
versed spade
#

🀦

leaden ice
#

As it will change as the game goes on

#

You can't just read the player input on the first frame and stop!

versed spade
#

yeahh was thinking that too. Glad I wasn't insane . Thx

leaden ice
#

!code

tawny elkBOT
rigid island
#

barely

tawny elkBOT
rigid island
#

jesus..

normal sail
#

lol

rigid island
#

do people read anymore

quaint rock
#

look thats a lot of text, (checks notes) its on the 2nd line

#

no one got attention for that

normal sail
#

Would this work?

// using UnityEngine;

public class ParkourController : MonoBehaviour
{
    public float jumpForce = 10f;
    public float wallRunForce = 5f;
    public float wallRunDuration = 1f;
    public LayerMask wallLayer;

    private CharacterController characterController;
    private bool isGrounded;
    private bool isWallRunning;
    private float wallRunTimer;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        Jump();
        WallRun();
    }

    void Jump()
    {
        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            Vector3 jumpVector = Vector3.up * jumpForce;
            characterController.Move(jumpVector * Time.deltaTime);
            isGrounded = false;
        }
    }

    void WallRun()
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.right, out hit, 1f, wallLayer) || Physics.Raycast(transform.position, -transform.right, out hit, 1f, wallLayer))
        {
            if (!isGrounded && Input.GetButton("Jump"))
            {
                isWallRunning = true;
                wallRunTimer = wallRunDuration;
            }
        }

        if (isWallRunning)
        {
            Vector3 wallRunForceVector = Vector3.up * wallRunForce;
            characterController.Move(wallRunForceVector * Time.deltaTime);
            wallRunTimer -= Time.deltaTime;

            if (wallRunTimer <= 0)
            {
                isWallRunning = false;
            }
        }
    }

    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        if (hit.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
        }
    }
}

rigid island
#

@Inject knowledge

#

soon ℒ️

normal sail
#

so will this work?

spring creek
normal sail
#

I dont know where should I place it

#

like I only got the code

spring creek
#

@mental rover why are you clown reacting to so many people?

normal sail
#

in the character controller?

spring creek
tawny elkBOT
#

:teacher: Unity Learn β†—

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

mental rover
spring creek
#

Clearly just learning imo. Struggling
I mean eugen is OBVIOUSLY not trolling.
Fedle... maybe, but I don't think so

quaint rock
#

alot of people do not realize how many steps and work are involved and just kinda get overwhelmed and lose the trail

thin hollow
#

I'm trying to make coroutines serializable so that I could save and restore their state for game saves and persistent levels. Answers I've found online were either too vague to be of any use or said to move stuff outside of Coroutines to the Update function, which invalidates the entire idea of using coroutines in the first place as a convenient function that can be executed iteratively over time.
I've got here so far, a custom serializable class that will hold ref to the coroutine and execute it, but now I'm stuck, how to actually make use of the yield instructions that the coroutine returns? For example WaitForSeconds stores the seconds m_seconds, but it is internal and therefore cannot be reached from the outside.

        public ManualCoroutine(IEnumerator routine, bool paused = false)
        {
            this.routine = routine;
            this.paused = paused;
            routine.MoveNext();
            if(!paused) Subscribe();
        }
        private void Subscribe() => GameManagerGlobal.ManualCoroutinesTick += Tick;
        private void Unsubscribe() => GameManagerGlobal.ManualCoroutinesTick -= Tick;        

        internal void Tick()
        {
            if(!paused || elapsedTime<maxTime)
            {
                elapsedTime += isFixedTime ? Time.fixedDeltaTime : Time.deltaTime;

                if (waitingForSeconds < elapsedTime)
                {
                    if (routine.Current is YieldInstruction route)
                    {
                        recordedStep += 1;
                        if (route is WaitForSeconds wait)
                            waitingForSeconds = wait.m_Seconds + elapsedTime; // <- where to go from here if this doesn't work?
                    }
                    

                    if (!routine.MoveNext())
                    {
                        Unsubscribe();
                    }
                }
            }
            if (elapsedTime>maxTime) Unsubscribe();
        }
little meadow
#

move stuff outside of Coroutines to the Update function
+1 for that advice, really... coroutines are rather low control fire and forget things... for anything else is just kinda annoying to deal with them

#

but for the fun of it... what do you wanna do? save a coroutine's state in a file and then continue from where it last was on Load?

latent latch
#

if you want to serialize coroutines you're just saving w/e member data they add previously before destroying them, then when deserializing you're just reconstructing the whole thing and appending the databack.

thin hollow
little meadow
#

why would it fail?

#

(also, the more coroutines that control game logic - the sadder (lets call it higher risk of later annoyance, not a strictly bad thing))

latent latch
#

Update would probably make it easier though as populating lists would easier than restarting the coroutines

fervent furnace
#

Serialize coroutine should be impossible since you have to capture local variable values….maybe you can use reflection to find out the class generated

quaint rock
#

the want to Serialize a coroutine is strange to me

thin hollow
# little meadow why would it fail?

Well if I move the, say, WaitForSeconds functionality of routine into an Update, and it's a coroutine that spawns a bomb after 5 seconds, if I trigger StartCoroutine 4 seconds after the first one again, it won't spawn it a second later, it will begin to wait for 5 seconds to elapse again

latent latch
#

the only major difference between coroutines and update is that you can sleep coroutines, but otherwise you can manage everything in a single update

little meadow
thin hollow
#

A more concrete example, my game uses trigger interface system so that game objects could inbteract with each other. It can include a delay, so you press button and door opens only two seconds later or something. One object can have many targets it can trigger if it itself was activated in a certain fashion. So if I set one othe trigger targets to trigger after 10 seconds, but in this time player leaves the level to an adjacent one and then returns... trigger won't ever be completed, the sequence it was a part of is now broken.

latent latch
#

it's a bit more complicated, but you're just serializing flags in that regard

#

and figuring out where you last left off with those flags

hard viper
#

I use an IReadOnly interface to expose getters of some data structure, can C# compiler figure out to inline it?

thin hollow
# latent latch it's a bit more complicated, but you're just serializing flags in that regard

My previous solution was a class that imitates coroutine functionality through going througs a series of "if" statements and checking if this if's condition is true and its step matches the sequence progress, but it was not an optimal solution because I needed to create a new inheriting class for every new type of "manual coroutine" I needed, and it turned out it cannot use any private or protected variables.

mental rover
vagrant agate
mental rover
#

reconstructing the exact coroutine and its stages is awkward, constructing a new coroutine that simply starts with the remaining time from the last one isn't quite so bad

vagrant agate
#

Also the decoupling of your linked doors is a bad design

thin hollow
vagrant agate
#

Sorry, I meant the button and the door. Both of those "linked" items should share the same state to prevent syncing bugs

quaint rock
# thin hollow Why?

sorry miseed this, but i feel having this want or need in your project. just means your data and your logic are too tied to eachother

#

the game state should just be data that can be saved

#

not where you currently are in a enumerator

vagrant agate
#

especially if you are wanting to leave a level and return it needs to be saved somewhere

mental rover
#

if the state is "a door is going to open in 4 seconds", that's something important to save though - though it does sound to me like Darth is overcomplicating trying to serialize a coroutine object itself instead of the raw data of a door opening in 4 seconds

thin hollow
# vagrant agate Sorry, I meant the button and the door. Both of those "linked" items should shar...

Both of those "linked" items should share the same state to prevent syncing bugs
Uh... I don't quite understand what you're trying to say. I've seen plenty of things in games that happen after a delay from you doing something to trigger them. Cinematics, scripted sequences, puzzles...
especially if you are wanting to leave a level and return it needs to be saved somewhere
Well, that's the edge case I've found. I didn't intended the player to be required to leave level while sequence is playing out, but I've found accidentally that if you do - it breaks.

quaint rock
#

most games are very deliberate about what they save and do not save, not just wholesale trying to save the state of a whole coroutine object

vagrant agate
#

for instance using basic json:

{"door_one_unlocked": true}
...

scenario:

player press's button => door has a 10 second delay => player leaves before 10 seconds

solution 1: entering the level => just have the door opened already

solution 2: (to maintain the timer) = > save the door value and time remaining in a file or DDOL => upon reentering level, start a new coroutine with that wait time ?

thin hollow
# mental rover if the state is "a door is going to open in 4 seconds", that's something importa...

The raw data in this case is "there was a signal to open dor in 4 seconds 2.456 seconds ago". And, again, its a specific simple example, I have more complex coroutines, including those that have, say, several WaitForSeconds yields. How am I supposed to move that to the Update - create a bazillion of timers? And again, how to run two such coroutines simultaneously? The whole system grows in complexity very fast

quaint rock
#

its fine to repersnet the logic as corroutines or how ever makes sense

#

the issue people are pointing out is you cna jsut save a whole coroutine

#

a coroutine is such large moving target to serialize, its state can be effected by pretty much anything in your game at any point in time

#

and contains logic not data

#

also say you could do this, and you return to the level? does it just skip to the part of the coroutine you want?

#

what happens to all the state the coroutine would have modified to get to that point, if it skips it

thin hollow
quaint rock
#

and part 2 of my question

#

if it skips to a point everything before that would not be done

thin hollow
quaint rock
#

so really you just want a crap load of ifs in your coroutine tracking if flags have been set or not to skip sections

#

and wait steps that can take in the remaining values

vagrant agate
#

my head hurts just thinking about programming that design

quaint rock
mental rover
thin hollow
# quaint rock so really you just want a crap load of ifs in your coroutine tracking if flags h...

"A crapload of if's" is how my first attempt at making serializable coroutine went πŸ˜„

        [Serializable]
        public class CR_Player_Stun : CR_Routine
        {
            internal float stunTime;
            internal override void Update()
            {
                if (Begin())
                {
                    player.isStunned = true;
                    InputControl.Instance.SetControlState(ECState.Character_NoMove);
                    player.meshAnimator.SetBool("Stunned", true);
                }

                if (WaitForSeconds(stunTime))
                {
                    player.isStunned = false;
                }

                if(WaitForSeconds(1))
                {
                    if (!player.isStunned)
                    {
                        InputControl.Instance.SetControlState(ECState.Character);
                        player.meshAnimator.SetBool("Stunned", false);
                    }
                    Disable();
                }
            }
        }

But that approach has the previously mentioned problems of each coroutine needing to be a new subclass and it being unable to access anything not public from the object that triggers it.

quaint rock
#

hmm maybe each state changing operation is implemented in a command, and you push them onto a stack

#

each command has a method for instantly applying and applying over time

latent latch
#

waitforseconds is kinda problematic as you do want to be tracking the time yourself if you are to serialize it

quaint rock
#

like having the exact waits how important is this, feel if it did not happen when loading back getting the full wait agian is fine for how most games work and what players expect

thin hollow
# latent latch waitforseconds is kinda problematic as you do want to be tracking the time yours...

Yeah, the base class had everything to trach and save that for serialization. Update() gets called from Tick(), which subscribes to even in my game manager on the activation of ManualCoroutine, and records how long it was active

        private void TryAdvance(bool result)
        {
            if (result)
            {
                recordedStep += 1;
                elapsedLastStep = elapsedTime;
            }
            step += 1;
        }

        /// <summary>
        /// <para>Wait for the set amount of seconds.</para>
        /// </summary>
        internal bool WaitForSeconds(float seconds)
        {
            bool result = (elapsedTime >= elapsedLastStep + seconds && step == recordedStep);
            TryAdvance(result);
            return result;
        }

vagrant agate
quasi sorrel
#

!code

tawny elkBOT
mental rover
thin hollow
quasi sorrel
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerShoot : MonoBehaviour
{
    public Transform playerGunBarrel;
    public GameObject Range;
    // Start is called before the first frame update
    
    public void Perform()
    {
        
     if (Input.GetKey(KeyCode.F))
     {
         PShoot();
     }
     

    }
    public void PShoot()
    {
        //store a reference to the gun barrel.
        //instantiate a new bullet.
        GameObject bullet = GameObject.Instantiate(Resources.Load("Prefabs/Bullet") as GameObject, playerGunBarrel.position, Range.transform.rotation);
        //calculate the direction to the player.
        Vector3 shootDirection = (Range.transform.position -  playerGunBarrel.transform.position).normalized;
        //add force to rigidbody of the bullet.
        bullet.GetComponent<Rigidbody>().velocity = Quaternion.AngleAxis(Random.Range(-3f,3f),Vector3.up) * shootDirection * 150;
        Debug.Log("Shoot");
    }
    

    // Update is called once per frame
   
}

Anyone know a way I can "Slow down" the Input.GetKey function so that the bullets don't come out of the gun every frame the key is held down?

latent latch
#

on the topic of coroutines, you can try coroutines

#

or use a timer comparison

quaint rock
#

tracking all of that over a whole game is alot

vagrant agate
#

if the player left from a level and went back, most people do not want to go back through a cut scene, start the player at the next step

quaint rock
#

it feels like a step is too large

vagrant agate
#

sounds like to me , create a database design for state management for all your cut scenes

quaint rock
#

like the half-life example, generally 1 scripted sequence is triggered by where the player currently is, or by the end of the previous scripted thing

#

thus if you save mid thing, and load it will replay it

#

but if you save and reload after a step you are fine

#

so feels like smaller coroutines, and at the end of one you save a flag, so something else can see that flag change and start its stuff

thin hollow
# quasi sorrel ```cs using System.Collections; using System.Collections.Generic; using UnityEng...

Something like that maybe?

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

public class PlayerShoot : MonoBehaviour
{
    public Transform playerGunBarrel;
    public GameObject Range;
    private float firerate = 0.7f // the rate of your fire in seconds between shots;
    private float lastFireTime =0;
    // Start is called before the first frame update
    
    public void Perform()
    {
        
     if (Input.GetKey(KeyCode.F))
     {
         PShoot();
     }
     

    }
    public void PShoot()
    {
        if (lastfiretime > firerate)
        {
        lastfiretime = 0;
        //store a reference to the gun barrel.
        //instantiate a new bullet.
        GameObject bullet = GameObject.Instantiate(Resources.Load("Prefabs/Bullet") as GameObject, playerGunBarrel.position, Range.transform.rotation);
        //calculate the direction to the player.
        Vector3 shootDirection = (Range.transform.position -  playerGunBarrel.transform.position).normalized;
        //add force to rigidbody of the bullet.
        bullet.GetComponent<Rigidbody>().velocity = Quaternion.AngleAxis(Random.Range(-3f,3f),Vector3.up) * shootDirection * 150;
        Debug.Log("Shoot");
        }

        lastfiretime += Time.deltaTime
    }  

    // Update is called once per frame
   
}
quasi sorrel
#

thanks, let me try it out

#

i tried something similar before

lean sail
#

notlikethis Resources.Load every time you shoot

#

You can just drag the bullet into a GameObject field, which is both better and let's you plug in different prefabs for different instances of the script

vagrant agate
#

that on top of no pooling lol

thin hollow
lean sail
#

Pooling isnt needed 100% of the time. Sometimes it can be more of a hassle

quaint rock
#

also how to properly reference assets should come first

covert swift
#

why is my world space ui not interactive when im using a output texture on my camera?

spring creek
covert swift
spring creek
#

And?

#

Do you have the button set up with the OnClick callback?

rigid island
spring creek
#

Do you have an event system in the scene?

#

What code does the onclick method link to?

#

Gonna need more info provided instead of dragging it out of you 😸

covert swift
#

but not when i use the render texture

covert swift
rigid island
covert swift
#

it dosent click

rigid island
#

yeah thats a flop nvm

#

I just got around this ages ago by just using pixel shaders and stop doing the RT thing

celest iron
#

Why am I getting a Json parse error here?
https://pastebin.com/Hpj8zX9G
As you can see on the log, it is getting the correct path to the json, so I don't know what is wrong?

#

It is also impossible to be the wrong type, as I'm serializing WorldData

modern creek
lean sail
#

Json is probably messed up

celest iron
#

{"seed":414792,"name":"","id":"2024_03_08_162118"}

#

Maybe the empty name?

modern creek
#

try with a non-empty name

celest iron
#

K, just a sec

modern creek
rigid island
#

is that the file though or what the method is getting ?

modern creek
#

i'd imagine that's the content of the file

celest iron
#

Even with non-empty name, still same error

lean sail
#

Your debug is also after the parse, print the name beforehand

celest iron
lean sail
#

I think you may be looking at the wrong file

rigid island
#

print whats happening in the code

lean sail
modern creek
#

also paste/post your World data struct

celest iron
#

Wait, ToJson don't serialize lists?

rigid island
#

it should

lean goblet
#

If the data types from the list are serializable, then yes, ToJson serialize it.

rigid island
#

WorldData is Serializable yes?

celest iron
#

Yes

#

What about Hashset?

lean goblet
#

Is your function getting the right JSON string value?

rigid island
#

maybe cause its a prop ?

celest iron
rigid island
#

haven't use JSON util in ages

#

i stick to newtonsoft

modern creek
#

oh

#

i see your problem

#

you're trying to deserialize the path of the file, not the contents

celest iron
#

oh

quaint rock
modern creek
#
        string[] worlds = Directory.GetFiles(Application.persistentDataPath, "world_*", SearchOption.AllDirectories);
            WorldData worldData = JsonUtility.FromJson<WorldData>(worlds[i]);
modern creek
#

what you want is probably more like this:

List<string> worldFilenames = Directory.GetFiles( blah bla blah );
foreach (string filename in worldFilenames)
{
  string content = File.ReadAllContent(filename);
  WorldData world = JsonUtility.FromJson<WorldData)(content);
}
celest iron
#

oooooh

#

yeah

#

lmao

#

I forgot the Read

#

Lemme try it

celest iron
modern creek
#

πŸ‘

quaint rock
#

so i normaly do not use JsonUtil since its pretty limited in types and features

#

but types wise its all the same stuff you can show in the inspector

#

so you can use that as a quick way to test

modern creek
#

yeah but proly fine for code-general/beginner.. but yes, later on you're gonna wanna use NewtonSoft or another "real" json parser

celest iron
modern creek
#

or go πŸ’ͺ and use MessagePack

rigid island
#

hell even the microsoft one supports more

modern creek
#

πŸŽ‰

celest iron
#

Yeah, gonna change to NewtonSoft

#

I'll have to serialize dictionaries later anyways

#

I hope newtonsoft can do it?

rigid island
#

yup

quaint rock
#

yup

celest iron
#

That's great, thanks for the help guys

quaint rock
#

if it did not i would be screwed got lots of dicts in my save logic

rigid island
#

funny enough I knew it was using newtonsoft when i got a Self referencing loop detected error from trying to use Vector3 in the Unity Cloud Save

rigid island
#

nicee! iirc you just had to disable some setting it was like an option thing, but yeah sadly that only works for your client side .
the one unity uses for Cloud Save is on their server so this cant be done on their end

#

since for Cloud Save you have to send a Dictionary it uses json.net on the server side to serialize it

quaint rock
#

yeah never used cloud save

#

always used our own binary formats for saves, and in some projects playfab

ripe mountain
#

hey everyone i had a rotation script that i know works but i cant get the gem to rotate any help?

rigid island
#

start by sharing the script

ripe mountain
#

ive put the script onto the gem but cant get it to rotate in game

public class RotateScript : MonoBehaviour
{
//Rotational Speed
public float speed = 0f;

//Forward Direction
public bool ForwardX = false;
public bool ForwardY = false;
public bool ForwardZ = false;

//Reverse Direction
public bool ReverseX = false;
public bool ReverseY = false;
public bool ReverseZ = false;

void Update ()
{
    //Forward Direction
    if(ForwardX == true)
    {
        transform.Rotate(Time.deltaTime * speed, 0, 0, Space.Self);
    }
    if(ForwardY == true)
    {
        transform.Rotate(0, Time.deltaTime * speed,  0, Space.Self);
    }
    if(ForwardZ == true)
    {
        transform.Rotate(0, 0, Time.deltaTime * speed, Space.Self);
    }
    //Reverse Direction
    if(ReverseX == true)
    {
        transform.Rotate(-Time.deltaTime * speed, 0, 0, Space.Self);
    }
    if(ReverseY == true)
    {
        transform.Rotate(0, -Time.deltaTime * speed,  0, Space.Self);
    }
    if(ReverseZ == true)
    {
        transform.Rotate(0, 0, -Time.deltaTime * speed, Space.Self);
    }
   
}

}

rigid island
#

ok and you have no bools checked in the screenshot you posted @ripe mountain

#

also next time post !code as follows ⏬

tawny elkBOT
mystic sapphire
#
  [SerializeField] UnityEvent lights; //I want the option to click the + button and add the amount of lights I need per thing I'm doing


    [Header("Timers")]
    public float timer;
    public float minTimer;
    public float maxTimer;

void Start(){
    timer = Random.Range(minTimer, maxTimer);
}
    void Update()
    {
        FlickerLight();
    }

    void FlickerLight()
    {
        if (timer > 0)
        {
            timer -= Time.deltaTime;
        }

        if (timer <= 0)
        {
            //How can I make it so the amount of lights I have added get enabled / disabled here?
            timer = Random.Range(minTimer, maxTimer);
        }
    }
}

Hey everyone. I made a script where at the start I had 4 gameobjects which were lights and they all either turned on / off depending on the timer, but recently I have been needing more in one script but I don't want to add loads of gameobjects so I found the UnityEvent where I can then press the + button and add the amount I need but doing that means the light.enabled = !light.enabled didn't work anymore. What can I replace that bit of the code with instead?

rigid island
mystic sapphire
#

I didn't actually think of that

mystic sapphire
plucky lance
#

Anyone got a good tutorial on UI like more advanced stuff like a back/ previous button and stuff

plucky lance
#

Like a back button

rigid island
plucky lance
#

It's just annoying and confusing enabling and disabling ui elements

vagrant blade
#

The functionality for going back has nothing really to do with UI. The UI side is as basic as it gets: a button that calls a function.

plucky lance
#

No I know. It's a design thing but I was wondering if someone like had a good system and stuff

vagrant blade
#

None I can recommend. Just what I do, use a bunch of subcanvases and turn them on and off based on some controller managing the state of the menus.

idle river
#

Anyone have any ideas on going about making a fighting game?

#

Specifically the motion inputs

rigid island
#

this question is as vague af

idle river
#

Sorry I meant like quarter circles, half circles

#

Z-motion

#

Stuff like that

cosmic rain
#

Still no clue what you're talking about. Try using more common words. Not everyone here has a grasp of fighting games vocabulary.

midnight sun
#

Can somebody help me identify why Unity freezes indefinitely whenever I enter playmode after this code is ran?

/// <summary>
/// Create a new entity instance managed by the object pool.
/// </summary>
public static Entity Precache(ID id)
{
    // Create instance.
    Entity source = Resources.Get(id);
    Entity instance = Object.Instantiate(source);

    // Pool instance.
    Mark(instance);

    // Output instance.
    return instance;
}

Once the entity is instantiated, the freeze occurs, but only if a serialized bool property is false on the entity component. Keep in mind, the bool has no references besides the declaration in the entity class.

lean sail
midnight sun
rigid island
midnight sun
#

I've only attached my entity script which essentially stores meta data, it doesn't do anything in particular.

#

All assigned in inspector btw

lean sail
#

This is very vague, check to see if what I said above is happening. Likely an object spawns itself which spawns itself which...

#

Also attach the debugger so you can go through your code line by line and not freeze your unity uncontrollably

midnight sun
#

Looking through my git commits, the bool recently changed on the commit that I thought caused it, but this issue appears to be far older than I realized. I'll come back with some more info if I'm still having trouble.

#

And I thought I was going crazy by how little the changes should've impacted my project.

lean sail
#

if swapping a bool causes ur game to freeze, you should really fix that

midnight sun
#

Truly a blunder of all time.

#

At least it's only two days worth of changes.

idle river
dense estuary
#

Is there a way I can use a raycast that rotates direction instead, like, is there a sort of plane cast I can use so I can make it really tall?

latent latch
#

Like boxcast?

dense estuary
#

oh, probably

#

my bad

woeful narwhal
#

is there a way i could cycle through all the items in "GameInputs" with an index? for example GameInputs[0] would be select one and so forth (in the input system)

heady iris
#

You can make an array of InputActionReference

#

This type lets you serialize a reference to an input action (surprise!)

woeful narwhal
#

oh alright thats good to know! Ill give it a try

woeful narwhal
heady iris
#

Yeah, it's really nice. I use it for basically everything.

#

I just wish there was an InputActionMapReference, too..

#

the comments for InputActionReference mention wanting to implement that

woeful narwhal
#

yeah that would be nice

dense estuary
#

How can I make a boxcast spin? I want the direction to spin clockwise on the y-axis. Currently I am trying to add 1 to the directions y value every frame, but that changes the position of the end of the boxcast.

vagrant blade
#

You want it to spin while moving forward? πŸ€”

dense estuary
#

no

#

I want the raycast to spin similar to how a radar scanner's soundwaves spin

#

that line, spinnning

latent latch
quaint rock
#

would use a regular raycast every frame

vagrant blade
#

A cast takes a direction and length, that's all. So create a direction, and rotate it every frame and boxcast with that direction.

dense estuary
latent latch
#

technically you can use a spherecast here and check a set angle/direction

quaint rock
#

sphere or box is fine too

vagrant blade
#

You shouldn't be raycasting then

#

Grab all the nearby objects and check angles

quaint rock
#

but you are firing them off each frame rotationed a bit more

vagrant blade
#

What Mao said lol, whoops

quaint rock
#

or overlapsphere actually

latent latch
#

right overlap

quaint rock
#

for the whole radius and just calcualte the angles of everything caught

dense estuary
quaint rock
#

well you are talking about the logic part

dense estuary
#

well, I was using overlapcapsule

quaint rock
#

the casting is just about logic

#

the visual you deal with seperatly

dense estuary
#

I was thinking I could redesign the logic to match the visual

#

but that would probably work too

quaint rock
#

that would cost much more

#

much easier to get everything, calculate the angles then do the visuals with that information

#

as the visual part of it is rotating, you would know its angle, and can use that to figure out from your objects which ones are udner it in that point in time

twilit scaffold
#

Is VS ignoring self made Snippets, basically randomly, a known issue?

keen smelt
#

Hi team

#

I am looking to Object Pool my projectiles. I will have different types of projectiles, so many pools.

#

I have a scriptable object for each type of projectile, with the prefab, etc

#

I want to have a Global Object Pooler singleton

#

that all the projectile stats SOs add themselves to a list on Awake, and then on Start, the global object pooler will go through all of them, and count how many of each projectile there is

#

based on that number, it will create a pool for each projectile and make the max amount of pooled objects based on how many weapons for that projectile there are.

#

The only issue I have it,

#

I need to dynamically create all these object pools.

#

So as far as I`m aware, C# doesn't let you create variables from a string or anything like that, aka "objectpool name = new object pool" where "name = weaponstats.prefab.name"

#

So am I stuck with just making individual object pools for each instance of the weapon?

#

because that's where I can make these variables in advance. I'll have potentially many multiples of the same pool, instead of one big one. Seems like a waste.

#

Anyone have a suggestion?

#

I hope this makes sense.

latent latch
#

why are you using strings

#

create by type

remote dirge
#

Hey, I'm not sure if this belongs here of the beginner channel, but I figured I'd ask: is it good to have most of the meat of the game be in one script in an attempt to avoid spaghetti code? Right now that's what I'm doing and I'm not sure if it's a good idea. Thankfully my game is still in its very early stages so there's plenty of time to fix it if needed.

#

I ask this because my earlier attempts at making a game in Unity were plagued by spaghetti code, and I'd like to try and avoid it for this project.

latent latch
#

Usually it's the other way around. Avoid spaghetti by dividing up your scripts.

remote dirge
#

Okay, so instead of having my main currency manager, shop manager, and stat manager in one script, I should have them each in their own scripts?

#

I'm just trying to make sure if I understand this right.

latent latch
#

Unity kinda forces you to use separate scripts anyway if you've got multiple non-nested classes in a single script because it's ambiguous to the editor when assigning stuff on it.

#

For anything that derives from mono that is.

remote dirge
#

Okay. My only problem is that I'd have to probably singleton them because of the nature of the copper needed to buy things from the shop and increasing stats. Then again, if I have to, I guess a few singletons wouldn't hurt too much. I just don't want to overdo it like my other previous projects.

crude mortar
#

another important question is whether or not it matters if it's spaghetti code in your particular case. in my experience, planning for infinite expansion of code is just unrealistic, and if you are making a relatively simple game, I would just go with what works. I do think you should split things up somewhat, but don't split it up too much until you actually know why you are splitting it up (as in, you run into a tangible issue or have some reason to split it further). The "manager" approach usually is spaghetti code, but it may not matter much in the long run if the game functions

#

definitely better than having the whole game in one file though

remote dirge
#

That is true. I'll try splitting them up and see how far that goes. Like I said, my game is in its very early stages so far, so it shouldn't be too hard to fix this problem.

crude mortar
#

many published games have a lot of singletons set up as you described above

latent latch
#

You can always add secondary layers to your singletons to decouple them a bit more (service locator patterns), but beyond something like a GameManager, there's always ways to bind and find those references.

#

i.e, if GameManager has an AudioManager reference, you don't need to make AudioManager a singleton since you can simply reference GameManager.

tall salmon
#

I want to make an explosion like particle but dont know how to call it with code so it happens at certain given time and i cant manage to find any video that says how, does anyone know how to do it?

tall salmon
#

i want to make a particle system pop up whenever i kill an gameobject

#

but i dont know how to call that function with code and cant find anything related

rigid island
#

might want call ps.Emit() each time

tall salmon
#

so i should create a variable called particle system and then whenever i want to call it write ps.emit() ?

#

or well it would be particleSystem.emit?

tall salmon
#

no clue what all that means

rigid island
#

just call the method

tall salmon
#

english is not my main language and its kinda hard to understand

#

how do i do that?

#

and how can i make it produce no particles until i call it

rigid island
#

the way you said it

#

disable Play on awake

tall salmon
#

Ohhhhh

#

true

#

ty!

#

ill try it

#

can i ping if it somehow doesnt work?

#

@rigid island so its not a code issue since im making the particle itself first

#

how do i make the particles take a certain colour?

#

more than take, the word im looking for is "be"

#

nvm it seemed to solve itself alone

#

i had the start color part set to a red-ish but it came out as purple, restarted and now it works

#

epic

#

@rigid island i have a code issue now

#

xD

#

since i trigger it when the game object has a float set to 0 (the float is the amount of hp) it instantly deletes afterwards

#

so what i thougt on doing was making the sprite invisible and remove the collider ( so it cant take any hp from the player) and once the particle system ended doing 1 cycle destroying the gameobject

#

how can i change the sprite to none?

#

here is a ss of what i have atm

#

ignore the variables that arent showing in the ss

spring creek
# tall salmon

You can just set the enabled state of the spriterenderer to false

tall salmon
#

ohhh

#

and how can i make it to wait until 1 particle cycle ends?

#

with a ienumerator?

#

havent used one in a while but i think i remember how they work

spring creek
#

Yeah, you can with a coroutine

#

(Which is a method that returns IEnumerator)

tall salmon
#

what was a method again?

#

if you can ping me in case you still here whenever you answer it would be nice (since im multitasking and trying to mess with whatever im doing in the code)

#

oh i messed up big

outer otter
#

i feel professional now that i setup github lol

tall salmon
#

BHAHAHAHHA

#

im scared of github

outer otter
#

its actually incredibly easy

#

download a program, login to github, 4 or 5 lines of code and its on github

#

roblox head over here explains it well

tall salmon
#

amazing

tall salmon
#

how can i record my screen ?

outer otter
#

haha his head looks like its about to get put on a stick and roasted loll

#

snipping tool

tall salmon
#

bro seems like he can sprint and jump while holding (idk how much but a big number) of golden block apple stacks

outer otter
#

boooo

#

you look like spongebob when he realized Sandy didnt breathe water

tall salmon
#

amazing

outer otter
#

lol

#

is it more efficient to send my github link if an issue could be anywhere in the project?

tall salmon
#

so the think is that idk how or why

#

but it does more than 1 cycle and more than 3-5 "particles" per cycle

outer otter
#

im gonna be honest i really dont feel like it haha

tall salmon
#

it makes total sense

outer otter
#

that would be the point of setting up github

tall salmon
#

im just checking if someone would help me

tall salmon
#

github scary

glossy wave
# glossy wave it spawned in the correct position before installing the physics addon. suddenly...

Solved it. My bullet consisted of an empty parent GameObject with a Physics Body and Physics Shape in it, plus a capsule child GameObject for visuals. I found out that the capsule had a Capsule Collider component attached to it, which somehow broke things. I removed the component and now the bullet spawns in the right location (sorry this isn't a code related problem anymore, but it's solved now )

#

How do i get rid of this message?

quartz folio
dawn nebula
outer otter
#

im trying to basically delete a repository and start from scratch using git. how can i remove the repository without risking deleting the entire folder on my local drive

faint hornet
#

** SOLVED solution in code block**can someone tell me why this function is not working? i feel like its a very small issue. all tiles seem to be disappearing at the same time and i want to stagger them with the while loop. wait for those to finish and then destroy all of them to make room for new ones.

here is the code:

public async Task UnloadLevel()
  {
    List<Task> tasks = new();
    pointDictionary = new();
    float elap = 0f;
    int count = 0;

    tasks.Add(levelTiles.transform.GetChild(0).GetComponent<TileElement>().GrowShrink(false));
    count++;

    while (elap < 1f)
    {
      elap += Time.deltaTime / 1f;
      if (elap >= 1f)
      {
        tasks.Add(levelTiles.transform.GetChild(count).GetComponent<TileElement>().GrowShrink(false));
        elap = 0f;
        count++;
      }
      if (count >= levelTiles.transform.childCount) break;

      await Task.Yield(); <-------- I FORGOT THIS LINE!!!!!!
    }

    await Task.WhenAll(tasks);

    while (levelTiles.transform.childCount != 0)
    {
      Destroy(levelTiles.transform.GetChild(0).gameObject);
      await Task.Yield();
    }
  }
chilly surge
outer otter
#

yea, i got confused and committed the entire project folder instead of just the asset folder. Im not sure exactly which set of folders i need to store in the repository

#

and i dont know if ive pushed it or whatever, its not showing anything in github, but git status doesnt show anythiung

chilly surge
outer otter
#

yea im settin it up now

#

what folders are necessary for unity ?

#

im guessing just the assets?

chilly surge
#

That gitignore template tells you which ones are necessary πŸ˜‰

#

Just copy pasting the template should work for most projects.

outer otter
#

okay, i shot myself in the foot lol

#

cant i just create a brand new repository?

chilly surge
#

I mean yes you can, but creating an orphan branch is easiest and you have the option of going back to the old branches so you won't run the risk of messing things up and losing all your progress.

#

Unless you are talking about GitHub repo not a git repo.

outer otter
#

github repo

#

but i honestly dont care about either, im not tied to whatever i did in git so far.

chilly surge
#

But you do care about the actual files right? And git/GitHub ensures you won't lose your progress.

outer otter
#

yes 0,0

#

i really dont like how easy it is to delete everything XD

#

okay so ill do what u said,

chilly surge
#

Here's what I would do:

  • Remove the GitHub remote from your git repo.
  • Create a new orphan branch, fix up your gitignore, commit.
  • Create a new GitHub repo, add it as the remote.
  • Push only the new orphan branch.
  • Now you are safe to delete the old GitHub repo, and the old branches.
#

At any point in time during this process if you mess up/regret it, you still have the old branches/old GitHub repo to ensure none of your work would be lost.

outer otter
#

remove github remote?

chilly surge
#

Yeah so you won't accidentally push to the old GitHub repo anymore because you are going to remove the old repo later anyways.

outer otter
#

oh my brain hurts, this is probably an easy problem but ive been at it since 6

#

would git remote rm destination work?

chilly surge
#

Yeah that's the command.

outer otter
#

im not sure what the remote name is

#

ill try origin https:// yadayada

chilly surge
#

git remote -v (you can also Google these)

#

It's probably called origin.

outer otter
#

yes yes it is

#

now if i could just edit the .ignore file and commit that to github thatd take out some unnecessary work

#

but why didnt it show any files in Github if i committed and pushed it?

chilly surge
#

Create an orphan branch first, then do the edits and commit.

outer otter
#

i have, i named in master

#

does it matter what branch im in

chilly surge
#

Well, you should be in the branch you want to commit to.

outer otter
#

im guessing thats the new one

#

or even better, if i could untrack all the files except the ones i need

#

i dont mean to talk your eyes off, just talkin out loud

chilly surge
#

Creating an orphan branch, fix up your gitignore, and you can just add everything as staged.

#

The purpose of gitignore is so that the things you ignore will not be tracked, so you don't need to painstakingly hand pick which files to stage every time.

outer otter
#

okay, ill get back to u when i get some progress done

#

alrighty so i made the orphan branch, pulled a unity premade ignore file, saved it, ran commit in the new branch, and it loaded much faster this time. it seems to work out correctly

#

now all i have to do is push git branch -M master and ill be golden?

chilly surge
#

Yeah, remember to make a new GitHub repo and add that as the remote, since you said you don't want the old repo anymore.

outer otter
#

i dont mind using the same one, are u refering to git remote add origin https:...etc?

chilly surge
#

In that case yeah, you can just add it back and push.

outer otter
#

what does -u mean in push -u origin master?

#

im sorry im anoying myself, so many questions lol

#

i used git push origin master and now its taking much longer 0.o

chilly surge
#

Well it actually has to upload your committed files to GitHub, so that will take a while if your project is big.

outer otter
#

yea, beforehand, when i got the errors, it was much faster. it looks like it might take an hour when before it was 10 minutes

chilly surge
#

You are pretty much done after uploading anyways, just need to double check if you have committed/pushed all the files, and once you are satisfied you are free to delete the old branches both locally and on the remote in GitHub.

outer otter
#

okay, hopefully this time something pops up in github

rancid frost
#

How come my list of strings and list of (serializable) structs are not seriazlized but the list of objects is serialized

When I restart the program, the data in the list of strings and struct are lose

covert swift
#

why does this dubble the letters? hello = hheelllloo?

rancid frost
#

are you saving as u are typing?

#

are you editing the word as you are typuing

#

omg

#

ARE YOU EDITING THE STRING AS IT IS BEING LOOPED OVER

#

my goodness lol

covert swift
#

what

#

why are you so shocked

rancid frost
#

I couldnt type what I wanted to say lol, mb

#

Im saying

covert swift
#

ohhh

rancid frost
#

are you editing the variable as it is being looped over?

covert swift
#

no

#

it will be called in the start

rancid frost
#

create a debug.log statement

#

see if it prints out thesame letters

covert swift
#

where

rancid frost
#

below textComponent

covert swift
#

debug.log(textComponent.text)?

dusk apex
#

Print the typingTextString variabel before the foreach statament.

covert swift
#

ok

#

like this?

rancid frost
#

noo

#

in the loop

dusk apex
#

What did it print in the console?

rancid frost
#

print out each letter as u are adding it

covert swift
#

it prints two times so its somthing wrong

dusk apex
#

So your problem lies elsewhere

covert swift
#

yeah

#

thx

mellow sigil
#

You've started the coroutine twice

dusk apex
mellow sigil
#

If the log prints twice that means the coroutine has been started twice

dawn nebula
rancid frost
dusk apex
outer otter
#

@chilly surge

#

didnt seem to work, same thing, but it took like 2 hours longer :/

chilly surge
# outer otter <@451999506918277131>

Did you properly setup gitignore? Because Library/ folder should not be committed and the gitignore template I gave you earlier ignores that folder.

outer otter
#

yea it didnt include .gitignore, i added it, but my dumbass didnt commit it, i just pushed it.

rancid frost
outer otter
#

i got a file for it already

rancid frost
chilly surge
#

I gave them that already.

outer otter
#

i assumed the file was already added after saving the document text. I forgot after its modified it needs to be added back

chilly surge
#

Look at your local commit and check what files got included in the commit, it sounds like you messed up and committed all Library/ and other stuffs too.

outer otter
#

yea gitignore itself was ignored

languid hound
#

I'm trying to make an "unlit" or "textured" mode and was wondering how I can achieve this? I have this so far

public class UnlitLitTest : MonoBehaviour
{
    public bool unlit;
    public AmbientMode originalMode;

    public void Awake()
    {
        originalMode = RenderSettings.ambientMode;
    }

    public void Update()
    {
        RenderSettings.ambientMode = unlit ? AmbientMode.Flat : originalMode;
    }
}

But when it goes flat it becomes suuper dark. I'm trying to achieve what the scene view gives when you disable lighting. Any suggestions?

#

I can change the ambientLight colour but my concern is that if I cache the original value in a variable it'll change between areas and then the ambient light will be wrong when going back

mellow sigil
#

The component is on two objects or twice on one object

covert swift
#

oh my god im so dumb thanks

mellow sigil
#

or since the method is public there's a small chance it's being called from somewhere else

rancid frost
#

Why is the list of strings not being sereialized?

#

after game engine restarts, all data in list is gone

lean sail
rancid frost
#

data is populated

#

data is never unpopulated

lean sail
rancid frost
#

so essentially, user adds objects to list in editor, then for each object guid is created

lean sail
rancid frost
#

does this explain why the list of objects is saved but the strings isnt?

lean sail
rancid frost
#

yes

lean sail
# rancid frost yes

Yea then those save the same as if you modify a value on a component. It's different when setting it via script

rancid frost
#

I see thanks

plucky dagger
#

Does anyone know of a good functioning car controller that is free? The one I have allows the car to flip no matter what I do

#

I've gotten everything else working. My player can walk around my player can get into the vehicle It locks the player into the vehicle and they can drive around but my vehicle tips

lean sail
plucky dagger
#

That's what I've been doing. I've been modifying the current car controller script that I have that was a free asset and I've got it where I want it but no matter what I do to the wheel colliders I just cannot keep the car from tipping

lean sail
#

Modifying one will probably be more tedious then just making your own. If this is a rigidbody with no constraints, it is free to rotate however it wishes.

plucky dagger
#

Also the other question I have, is what would be a good way for my vehicle interact script to get the car I'm trying to enter

#

I guess I would need to put the vehicle interact script on the actual vehicles that way the script can get that particular game object