#archived-code-general

1 messages · Page 441 of 1

night harness
#

5 instances of your prefab pointing to 1 value stored in 1 SO rather than 5 values in the 5 prefabs

astral sky
steady bobcat
young yacht
#

you can have the first class be MonoBehaviour

#

then another class inherit from that first class

#

if thats what you mean

maiden monolith
#

https://paste.mod.gg/qfwicezbtatl/0
this is my wallrunning script.. for some reason, when i walljump (adding force to up and normal direction), the force to the normal of wall is not added properly... the u force works alright but the normal force is not added. it rubber bands me back to the wall. i've been stuck for a week, any help would be appreciated

cosmic rain
void ledge
#

Hello guys. I am trying to transit the scene from title screen to game scene. I have a intro animation that play at the start of the game scene, which is a combination of couples of small animation, and timed to play one after another. It synced perfectly if I start the scene in the Unity console directly but if I enter the scene by pressing button from the title screen, the animation would become buggy and the countdown sfx would delay by just 1 second. What could be the reason of this? Thanks!

compact socket
#

hello
i keep having this error :
'GetEmissiveColor': no matching 2 parameter function at (1)/Library/PackageCache/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitBuiltinData.hlsl(81) (on d3d11)

anybody know fix?

last quarry
compact socket
cosmic rain
#

Then regenerate the Library folder

compact socket
elder gust
#

wtf why is it doing this

vestal arch
elder gust
#

I have no idea I changed my script, unity crashed, I changed it back and it started spewing random stuff whenever I hit play

#

it worked fine before

vestal arch
#

well then it's probably to do with the stuff you changed

elder gust
#

but I changed it back so why is it doing this

vestal arch
#

define "worked fine before"
what do you expect to happen?

#

where's that logging from?

elder gust
#

I have no idea I double click it and it doesn't open anything

#

and by working fine before I mean the script did what it was meant to do and no random stuff was being spammed in the console

vestal arch
#

does the log not show where it's from?

somber nacelle
#

are those logs even coming from your code? if not, then you may just need to restart the editor

vestal arch
#

if they persist after that, maybe try deleting Library

elder gust
somber nacelle
#

probably just an editor bug, if i had to guess i'd say it's likely some corrupt memory or just some pointers that started pointing at the wrong memory 🤷‍♂️

void basalt
#

You know in helldivers when a pod lands next to you, your camera rotates up & away from the crash position?
How would you replicate that using quaternions?

vestal arch
#

pitch up and yaw away from the direction of the... explosion or whatever

void basalt
vestal arch
#

you don't need to write quaternions yourself

#

in fact you shouldn't

void basalt
#

I'm not asking how to write raw quaternion values. I'm asking how to use unity's quaternion API

#

or "how to use quaternions from a high level"

vestal arch
#

but you could get a quaternion from euler angles, and those would be using pitch/yaw/roll

vestal arch
#

specifically static methods for building quaternions, like Euler (or EulerAngles, i don't remember the exact method name)

void basalt
#

Respectfuly, you're of absolutely no help on this topic.

#

Sorry.

vestal arch
#

lol you wanted something and asked for something else

#

i pointed you to where you could find info on the thing you said you wanted

#

if you don't want the help just say so shrugsinjapanese

void basalt
#

What I asked for was pretty straightforward. You saying "just go to the docs bro" and "just pitch up bro" doesn't help me understand the proper way to manipulate a quaternion.

vestal arch
#

how to use quaternions at a high level, unity's own quaternion api, is described at length in the docs

void basalt
#

Nevermind, Just forget it

vestal arch
#

this is, again, laid out in detail in the docs

#

docs should be the first resource you look to lol
if you ask about something that's in the docs, don't get surprised when you get directed there

if you have a specific question about a specific manipulation that you don't understand the docs for, then ask about that

just asking about "how use quaternion" will just point you to docs, we can't read your mind for what you actually need. you gotta communicate it.

void basalt
#

christ

vestal arch
#

hey, im just being preemptive here lol. help is a two-way street.

lean sail
# void basalt You know in helldivers when a pod lands next to you, your camera rotates up & aw...

really first thing id do is use cinemachine since im pretty sure it has functionality like this made in. Had to lookup gameplay for this so hopefully i saw the right thing, and it looks like the camera moves in this. Quaternions wont move your object away, it just rotates.
otherwise really you could just define your own shitty version of an animation (or use an animation possibly?). Like a list of quaternions/relative positions and move to them over time. They're still shown as euler angles in inspector, then use quaternion rotate towards or lerp and just assign that to the camera rotation

void basalt
#

Sort of just a response to an explosion effect. Camera rotates up, but up relative to the explosion

#

Would rather learn how to work with quaternions rather than use cinemachine or animations

#

So if the explosion was to the right of me, the camera would tilt to the left

lean sail
# void basalt So if the explosion was to the right of me, the camera would tilt to the left

There isnt really much to know about it truthfully. In most cases you'll end up using a few set of methods and then either directly set the rotation or add to your current rotation.
i think for that exact use case you could do something like this
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Quaternion.AngleAxis.html
then "add" that result to your current rotation which is quaternion multiplication
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Quaternion-operator_multiply.html

somber nacelle
void basalt
#

cinemachine doesn't scratch my learning itch

lean sail
#

also what i suggested above would likely be a pretty stiff movement. im sure cinemachine has more functionality to make it look much better. you can learn without cinemachine but i wouldnt avoid it for your actual game features

#

maybe a slerp between a start and end rotation would look better but ive never coded something like this myself

void basalt
#

is it inherently wrong to plug vector3 rotations into quaternions?

vestal arch
#

no

lean sail
#

if you need to create a specific rotation then you should pretty much always be doing it from euler angles. after its created, you would be doing quaternion math all the way after

fast forge
#

Yo whats up I have a specifc question that I'm sure has an answer but I can't find it and don't want to wait for a forum post, when using netcode to program in multiplayer, how can I define a player prefab that includes the character AND the camera that said character needs to use without parenting the camera to the player? The player rotates in such a way that updating the camera's rotation every frame still doesn't make it stay straight, but the player prefab needs a network transform on the player itself to track the position rotation etc, and the network manager won't accept anything other than the object with the network transform and other scripts(network object, network rigidbody, network animator)

latent latch
#

I would suggest client side camera if you're new to networking

fast forge
#

wdym cinemachine

#

also yes I don't know why you'd ever have a server side camera that sounds insane

#

other than like coop games

latent latch
#

you don't need to parent the camera with cinemachine, it uses virtual camera components that takes in a target transform

#

basically the client spawns a camera and those virtual cameras, they get the network player transform -> link virtual camera to transform

fast forge
#

does it have smoothdamp easing? I move the camera in relation to the character in the character movement script

latent latch
#

it has everything and is one of unity's more popular tools

fast forge
#

thanks

novel bough
#

Hi friends, i am trying to achieve hinge movement at runtime by clicking and dragging. when i click on cube with hinge i should rotate respecting the hinge joint, I tried by creating empty object then make parent it of clicked cube, and when object move with mouse cube rotates but this way is not working as i want.

using UnityEngine;

public class DoorDragController : MonoBehaviour
{
    public  GameObject anchorObjectPrefab;
    private GameObject anchorObject;

    private void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //Debug.DrawRay(ray.origin, ray.direction * 100, Color.blue);

            if(Physics.Raycast(ray, out RaycastHit hit))
            {
                Debug.Log(hit.collider.gameObject.name);
                anchorObject = Instantiate(anchorObjectPrefab, hit.point, Quaternion.identity);
            }
        }

        if(Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if(Physics.Raycast(ray, out RaycastHit hit))
            {
                anchorObject.transform.position = hit.point;
                hit.collider.transform.SetParent(anchorObject.transform);
            }
        }

        if(Input.GetMouseButtonUp(0))
        {
            anchorObject.transform.DetachChildren();
            Destroy(anchorObject);
        }
    }
}

cursive coral
#

Help me please what is this

cosmic rain
cursive coral
#

Actually it's solved now. It was just changing some build settings

cosmic rain
cursive coral
#

So nvm

cursive coral
trim schooner
worldly stirrup
#

I remade my input so it now has a manager, but when I try to jump, it doesn't jump most of the time

#

Manager code: void Update() { pauseOpen=pauseOpenAct.WasPressedThisFrame(); pauseClose=pauseCloseAct.WasPressedThisFrame(); moveVector=moveAct.ReadValue<Vector2>(); jumpActed=jumpAct.WasPressedThisFrame(); }

#

Code in the player controller: ```void Update()
{
xInput=inputManager.instance.moveVector.x;
doJump=inputManager.instance.jumpActed;
}

void FixedUpdate()
{
    float delta = Time.deltaTime;
    checkOtherSides();
    checkGround();
    angleRad = slopeDownAngle * Mathf.Deg2Rad;
    playerControllerFunctions.timer(delta, ref coyoteCount);
    if (grounded) playerControllerFunctions.timer(delta, ref lockCount);
    handleXMovement(delta);
    setGravity(delta);
    handleJump();
    applyMovement();
} private void handleJump()
{
    if (!hasJumped && coyoteCount > 0 && doJump)
    {
        dust.Play();
        hasJumped = isJumping = true;
        lockCount = 0f;
        Vector2 jump = jumpForce * (sloped ? slopeNormal : Vector2.up);
        velocity = grounded ? velocity + jump : new Vector2(velocity.x, jump.y);
    }
    if (cancelJump)
    {
        velocity.y *= jumpCut;
        cancelJump = false;
    }
}```
hasty canopy
#

Hello, I'm trying out photon fusion and building a multiplayer game. Right now just figuring out the ins and outs of the stuff. And making a simple character controller and simple animations.

Now the question I have is, is it advisable to use root animation in online multiplayer game?

I imported fusion's BR200 asset for study purposes and extend upon it. It's using unity's playable API

mellow sigil
spice estuary
#

Any ideas for how to efficiently spawn NPCs (or any object really) on a navmesh, without overlapping other spawned NPCs in the scene (3D)?
For example, for a simple wave spawn system then spawning x amount of enemies, but ensuring that a spawned enemy does on appear on top of another.
So far my idea is to use Navmesh sampleposition on a random spot around the player and then combine it with CheckSphere to see if it hits anything that isnt the ground layer, but since this is random, it could potentially take many attempts to find a spot with no enemy on it.

leaden ice
spice estuary
solemn shale
# spice estuary Isn't that mostly used for static objects though?

You would have to keep track of all the entities as they move around, as you're checking dynamic positions at runtime. It's a bit more overhead and there's no guarantee you'll get a valid location, but otherwise it works the same. You could probably use a compute shader like what Sebastian Lague does for his flocking algorithm to improve performance.

Also, this might help as it's related to your question:

https://www.youtube.com/watch?v=ieuC39qv4x4

Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH

In this Unity tutorial, you'll learn how to spawn any object into your scene, and ensure that EVERY single time, they NEVER s...

▶ Play video
spice estuary
woeful hamlet
#

What's the easiest way to disable all player inputs (specifically for a quasi-cutscene at the end of the level to have the player drive away off-screen)? Can I just GetComponent<PlayerInput>().enabled = false; ?

rigid island
leaden ice
granite glen
# novel bough Hi friends, i am trying to achieve hinge movement at runtime by clicking and dra...

Not sure if anyone answered this yet, but I would resolve it by taking the distance between my mouses starting location and it's current location, and then based on that value I'd apply the force on that block at the direction you want, and then have it freeze if the mouse isn't moving anymore. Then as the mouse moves you apply force, but if it's doesn't move you don't apply force. This'll help with the constant juttering you get and allow the user to hold the block but still keep rigidbody physics. If you release your mouse, then the block unfreezes and we don't apply force.

safe fable
#

guys how do you manage your scripts. idk if im doing it right. i just have a scripts folder with 12+ scripts lol.
is that bad practice or does it not rlly matter as long as it works for me

#

16 scripts

#

should i like organize them in folders based on what they do?

steady bobcat
#

up to you i guess, organising them helps you out in future

#

e.g Scripts/UI, Scripts/Player

leaden ice
#

For example I have a folder for things related to my menus. Another folder for things related to the combat system. Another folder for the game data model, another folder for the save/load system, etc..

calm flame
#

My game project is going to need a fairly complex dialogue system

Multiple units, some static and guaranteed like bunkers, some instanced like scouting units, can have dialogue

The dialogue can be set firm and need to wait for flags (story stuff) or generated (orders for a bombing run or warnings to enable point defenses)

I'm trying to figure out the best way to organize and manage dialogue and conversations, and doing so that past transmissions can be re-read in the archive

My first thought is to create one script per static, permanent installation/unit and one script per generated unit type that holds the dialogue in lists and static variables for accessibility

So the main manager runs the code to generate the event list for the day, randomly rolls "Bunker 4 orders a strike," passes that info to the radio, the radio consults bunker4Dialogue.strikeOrderLines[random] and sends the resultant text string to the output box to be read when the player checks their radio

this is mostly a sanity check, this is my first time handling a system this large and complex I wanted to make sure I didn't overlook something much simpler or better

soft shard
# safe fable guys how do you manage your scripts. idk if im doing it right. i just have a scr...

Theres typically 2 common ways projects organize their files, either by "feature" where related files like models, sounds, prefabs, etc are grouped with the scripts in their own sub-folders, or by "type" where you have a "scripts" folder for all your scripts, a "models" folder and so on: https://unity.com/how-to/organizing-your-project

Personally, I prefer the former as its more specific and convenient having all the dependencies a script might reference in the same parent folder instead of trying to remember names to search the project with

Unity

Discover tips and best practices on how to set up your Unity project for team-based game development and version control. Read on for an in-depth guide.

mortal gate
#

Has anyone experience with floating RigidBody characters for movement? I have this script that floats my character (mainly to make the landing smooth so I do not just hit the ground) but because of gravity probably it never settles at rideHeight and that interferes with jumping mechanics. I have a RayCast at the lenght of rideHeight for finding the ground. Any ideas how to fix this? https://paste.mod.gg/tsvbnjjpxqzi/0

shadow cradle
#

im having trouble with firestore which doesnt support unity types like int, float and vector. i have to convert everything during serialization and deserialization. is there a better solution like a nosql db that supports those types or an easy way to convert the data?

eager tundra
# calm flame My game project is going to need a fairly complex dialogue system Multiple unit...

so, I would suggest inverting the responsibilities here
instead of having the units know about their dialogues, turn it into configuration for the dialogue system instead
this configuration would be some kind of mapping of unit ids to their dialogue lines (scriptable object, json, whatever works for you) and a centralized place for working with it (everything will be in the dialogue manager, not distributed between units), which should make it easier to replicate the lines to the "radio" or whatever else
the reason for this it to decrease the coupling between the units and the dialogues, now the units don't have to know anything about the dialogues anymore, which should make things more scalable

cosmic rain
#

And generally most programming languages have these types.

shadow cradle
# cosmic rain Int and float are C# types though. Not unity.

I know, unity uses c#. the problem is that the firstore sdk automatically converts them to long and double but heres the thing: not if they are stored in object fields, the remain doubles/longs. so im now trying a generic type interface as type in order to keep flexibility but keep the types

cosmic rain
shadow cradle
steady moat
# calm flame My game project is going to need a fairly complex dialogue system Multiple unit...

If you can, consider your "static" unit as "instanced" unit. It would reduce the complexity.
Utilize EventChannel to propagate whenever a dialog is said. By example, if you have localize dialog such as in between unit, you can publish an event on the channel. And if you do have "system dialog", you can still publish on the same channel. Make it transparent to whoever needs to listen/archive. (As a bonus, if you have other system that needs to listen to dialog they can use the same exact channel)
Centralize all your dialog into a single script. It would be easier to manage if you want to batch process them either for localization or search specific dialog.

elfin quest
#

Hello everyone. I'm creating an abstract MonoBehaviour derived class that acts as a middle man between monoBehaviour and final components. So my components will derive from this middle-man instead of monobehaviour directly, kind of NetworkBehaviour in netcode. I need some code to run on Awake on this middle class, but I run into the issue that I don't want to prohibit derived classes to use Awake, and I also don't want to force derived classes to call base.Awake, which leaves me in a very awkward position where I'd have to manually call a fake awake method on my middle class, but I'd have to perfectly match unity's native awake call, so I'd have to call this when the scene loads, when an object is spawned... Is there an elegant way to have another awake call without shadowing a derived component awake? (The same applied for the other magic methods like onEnable or start, I don't want to shadow any of these)

elfin quest
steady moat
steady moat
vestal arch
steady moat
vestal arch
#

ah i missed that mb

elfin quest
#

No worries, kind of a dense essay xdd

elfin quest
#

I could centralize them, yeah, but I still want the diferenciation between networked and non networked components

steady moat
# elfin quest Tbh, I was making my own networking system so yeah, pretty much my networkbehavi...

In that I case, I'm not exactly sure what you could do. Instead, I can say why it is a bad idea so you might atleast protect yourself.

If you create an intermediate class such as "RegistrableComponent" which is not necessary a NetworkBehaviour, you then find yourself in a ackward spot when you want to have both ("RegistrableComponent" and "NetworkBehaviour"). You cannot inherit from both.

#

So, if you are creating a library, whoever is using it (even yourself), is force to live with the choice you made. Which is a bummer.

elfin quest
#

Well, no, but in this case wouln't I just derive RegistrableComponent from NetworkBehaviour? If I really wanted non-networked behaviours to also be registarable I could do the reverse and inherit NetworkBehaviour from RegistrableComponent

night harness
#

can't you just call your "fake awake" from the final point of you accessing the real one?

elfin quest
steady moat
elfin quest
elfin quest
# steady moat Then all your RegistrableComponent must be NetworkBehaviour, which is definitely...

I mean I guess I would force library users to create a dedicated component to do the registering. Which is something I can live with, since I do belive in making every component as low responsability as possible for maintainability, and if a component is in charge of networking code, in my opinion it should just stick to that no? I do unserstand you, however I don't think It's that big of a deal

night harness
#

couldn't you just seal that off though? eg.

abstract BaseClass

virtual void Awake

abstract MiddleClass : BaseClass

override sealed void Awake
OnAwake()

virtual void OnAwake() {}

MiscClasses : MiddleClass

elfin quest
#

well yeah, but then u are stealing the awake from the derived and forcing it to use OnAwake, which is non-standard

#

I did explain in my original message that my issue was that I did NOT want to "steal" the unity magic methods

#

But again, I already solved that, thanks tho!

night harness
#

ok

steady moat
elfin quest
#

I guess yeah. I mean at the same time, almost every big networking library (That I know) uses this or a very similar method, so in the efforts of keeping integration seamless (by not shadowing), while maybe not the smartest way to implement network stuff, NetworkBehaviour is a well known and proven way of doing it no?

#

It's just In my case I created a unity-like very very small engine and my networking solution, instead of being server and client mixed, it works with unity for the client and the small engine for dedicated servers writen as pure dotnet console apps.

steady moat
elfin quest
#

100%

#

It's not release ready yet, but I think I'll be able to release it fairly soon, I think it's a very neat solution for people like me, that while liking the netcode-like flow, don't particularly like having server and client code mixed.

#

Thanks for the insights @steady moat

ashen otter
#

For my LeftStick Input Actions Binding, I simply could not find an option to replicate GetAxisRaw, and so the closest I've come is by code: csharp void OnMove(InputValue inputValue) { Vector2 inputAxis = inputValue.Get<Vector2>(); inputAxis = new Vector2(Mathf.Round(inputAxis.x), Mathf.Round(inputAxis.y));
But, I'm sure the Input System has an official way of doing this, right?

vestal arch
#

inputValue.Get<Vector2>() kinda is the equivalent of GetAxisRaw

fossil obsidian
#

guys I'm trying to make a working pc in my game and I'm testing the function to drag icons in the desktop, but when I release an icon, it doesn't fit the grid layout I've put in the panel (compare its position with the rest of the icons)

calm flame
# steady moat If you can, consider your "static" unit as "instanced" unit. It would reduce the...

What do you mean by that first sentence?

Are you saying I should generate all the dialogue handlers at runtime, rather than having the static ones hardcoded and the instanced ones generated at runtime?

The second idea is really good, thank you very much for the advice

It's much more future proof than my initial concept, and will make possibly implementing a feature on the "maybe if I have time" list (intercepting enemy comms) way easier

calm flame
# eager tundra so, I would suggest inverting the responsibilities here instead of having the un...

Thats a really good tip, thank you

part of the reason for the decoupling is that a large portion of the game involves using codes, ciphers, and various systems to obfuscate and decode information, so I'll have random weights determining which of the methods will be used for a particular bit of dialogue

so plaintext gets sent through a substitution cipher, then a SIGABA code, then finally output to the player, for example

I want replayability and variance, so I'm going to use randomness in which methods and what keys are used, this will also change which physical gameObjects will trigger and print/signal the information

If a message is rolled to be morse code, it needs to be converted and signalled, but if it becomes teletype ciphers, it needs to be sent to the printer to be instanced physically

calm flame
# eager tundra so, I would suggest inverting the responsibilities here instead of having the un...

on the subject of json vs scriptable object, does either have a particular advantage?

I've been doing more research and there doesnt seem to be a clear winner between json, scriptable object, or even just writing out string variables in large arrays

I want scalability, so I don't think I'll take the lazier option even though I'm a solo dev and the "easier for non-programmers" aspect of json doesnt benefit me

steady moat
calm flame
#

That makes sense, I'll try to do that, but it may end up being suboptimal

With the current plan, static buildings will always come in through wired systems and an operator board, and instanced units will always send messages through the radio transceiver

It couldn't hurt to attempt it that way, though, and it'll be easier to split the functions later if needed than merge them if I end up needing that instead

eager tundra
# calm flame on the subject of json vs scriptable object, does either have a particular advan...

most of the time this is just a matter of ease of authoring
if you choose to place everything in a large array you'll need to recompile your project on every change, increasing iteration times and also coupling your code with your configuration
you can solve this by providing configuration from an external source (scriptable objects, jsons, csv, etc.)

scriptable objects are fine inside of Unity, but it gets complicated if you want to modify them in bulk or author the data outside of Unity, like in a spreadsheet
json is just a popular format, it's human-readable, easy to modify and it's not coupled with Unity, so you could generate it from somewhere else and provide it even during runtime

#

I would suggest trying scriptable objects for this, then you can figure out the pros and cons later

calm flame
#

How broad would you suggest I go with the scriptable objects? One that can hold everything? Seperate it by sender?

The reason I ask is because there will be fairly large amounts of unique dialogue for each type of sender, but there will also be a lot of shared pools, like the one to generate firing orders, where a dynamic message will need to be generated based on a lot of game state information, with the prewritten sections gluing the line together.

ScriptableObjects apparently are not easy to modify at runtime from what I'm reading, for cases like that where I need to glue several peices of game information together to form the line it seems I might have to make an exception and handle them differently

steady bobcat
#

you can edit scriptable objects in bulk in editor easily, asset database to load em, modify and set as dirty ✨

eager tundra
#

that's easy for programmers, non-technical game designers not so much

rigid island
#

why not just using Json ?

eager tundra
# calm flame How broad would you suggest I go with the scriptable objects? One that can hold ...

it's hard to suggest anything specific without knowing a lot more about your project, maybe you could have one scriptable per unit containing all their messages and then link them under a common scriptable responsible for holding all the messages
I would not modify them during runtime though, your dialogue system should be responsible for generating the messages according to the configuration (scriptables) and parameters provided by the game state

steady bobcat
eager tundra
#

I doubt very much it would be noticeable in terms of performance, unless you're talking about many megabytes of jsons

rigid island
#

true, one the benefit of Json(files) allows you to add onto it besides inside unity editor. Maybe even a custom editor just for dealing with dialogue addition of new lines etc.

#

depends ofc how complex you wanna go

calm flame
#

One factor I think might change which is better, though at the moment the scriptableObjects are seeming like the much easier option to create the dialogue pools

I want to have an in-game archive of messages and conversations

the time and date the mesage is received will need to be recorded, as well as which decoding method was used, all of which are variable and will change on different playthroughs

This means saved data

Would storing those as JSON files be the way to go? If I need to use JSON to make the archive entries, would it be easier to just always use JSON, or would that be unrelated?

#

Scriptable objects for the pool and json for the saved files seems like the easiest solution

eager tundra
#

I would go with json for the data storage, yes

astral sky
#

Does the JSON Serialization from the serialization package support native types? That isn't mentioned anywhere in the manual

#

Guess not.

steady bobcat
#

Yea I'm not surprised it's not, you can use another serializer and make a converter to fix this

brazen nest
#

why is destroying game objects and recreating them so disastrous to performance, is it the reallocation of memory?

brazen nest
#

I want to know why the garbage collector causes a performance hit 😂 not sure where to find that info. Just pure curiosity is all

leaden ice
#

it's an actual process the computer has to do

#

And while it's doing garbage collection, it's not running the rest of the game

night storm
leaden ice
#

it completely bypasses C#'s memory management scheme

#

it's back to the basics of manually allocating and freeing memory more or less.

night storm
leaden ice
#

no

#

WE're basically talking about completely different abstractions so it's hard to talk in the language of Instantiate and Destroy in the world of ECS

#

you're basically always using native buffers and absolutely using and reusing the same buffers in memory

#

which is similar to object pooling

#

Basically we're stepping outside the world of Object Oriented Programming for the most part in ECS

night storm
leaden ice
#

No

#

Source is not an entity-component style engine

#

afaik

brazen nest
#

Native buffer kindof just sounds like a more primitive type of list of objects

quaint rock
#

source is not ECS style in the slightest

brazen nest
#

What does ecs mean

quaint rock
#

but it does do a bunch of custom allocation and uses memory arenas often

leaden ice
rigid island
night storm
#

does source handle this stuff better than unity with ECS would?

leaden ice
#

no

quaint rock
#

@night storm your questions are comparing apples to oranges

brazen nest
#

C++ you manage your own memory, C# does it for you?

#

Or Unity does it for you? Lol

leaden ice
#

C# does - hence the garbage collection

quaint rock
#

GC handles the memory for you, which makes many things easier but it comes at a cost and means less control over memory

brazen nest
#

Does Unity just build onto some abstract classes or something to make the garbage collection work for objects?

leaden ice
#

object pooling in a garbage collected language is sort of like preventing the GC from collecting memory so you can reuse it later, which is cheaper.

leaden ice
brazen nest
#

I haven’t worked in c++ yet much or with any garbage collectors and I sortof want to learn how they work

quaint rock
quaint rock
#

like in C++ to make a object you need to allocate memory for it, then would need to decide how and when to cleanup that memory

#

GC finds when memory is no longer used for you

brazen nest
#

Do you think it’s more efficient than C# because the program knows when to cleanup without stopping the whole game?

steady bobcat
#

The garbage collector analysing objects to find what to delete has a cost

brazen nest
#

Instead of searching a ton of memory, it searches the pointer you stored in code and de allocates it?

quaint rock
#

but if this was C your would have to write code yourself that de allocatates and choose when and where to do so

brazen nest
#

It stores pointers on its own?

quaint rock
#

and could leak memory if you failed

brazen nest
#

Right

safe fable
#

Hey guys! I just replaced my character from a capsule placeholder to my actual character. although the capsule was working perfect, the new model (although using the same exact scripts/etc.) doesn't rotate how it should, or how the capsule did. Although the new model moves and strafes correctly how it should, its not actually rotating front facing depending on what direction its going - unlike the capsule which DID do that. so im not sure what the issue is. Although im pretty confident the code isn't the issue, ill post it anyways (the bottom part function is just how i apply VFX effects to the character which is non affected)
https://paste.mod.gg/sudbagnhwzfb/0

thanks 😄

night storm
# quaint rock <@798203494279938049> your questions are comparing apples to oranges

i dont know anything about what either of them do under the hood, i know that you can spawn and destroy stuff a lot in source without any visible performance impact though, to the extent that would make default unity lag due to the garbage collector. would ECS be able to be as efficient as source in that regard? or would it use up more memory or something

steady bobcat
#

memory allocation/freeing is not free but will be faster than GC processing

quaint rock
#

also there are many many ways to avoid GC costs just by doing more reuse and structuring things better

leaden ice
# brazen nest It stores pointers on its own?

Let's say your program is like:

class A {}

A a = new A(); // we made a new object
a = new A(); // we maade a second new object. But what about the first one? It's an orphan now

In this example the first object we created is sort of lost to the void. It can't be used anymore by anything but it's still taking up memory. The garbage collector's job is to find object like that and get rid of them. The problem is, to do that it needs to basically look at all the references in the program and make sure none of them are pointing to the object. That's an expensive task. There are some optimizations but in general it's expensive. It also then needs to rearrange and recompact the memory and sometimes move objects around for example so it's easier to use the remaining free memory.

#

If this was C++ or something this would be a memory leak.

night storm
# quaint rock also there are many many ways to avoid GC costs just by doing more reuse and str...

well the reason i'm asking is because if i want to instantiate and destroy a lot of things i would need to make an object pool for each of those, and everything in the object pool stays there and takes up memory all the time, whereas source engine probably cleans it all up immediately. i was wondering if ECS was able to handle it like source without having to make a bunch of object pools

leaden ice
#

you write your code in C++

#

you are responsible for the cleanup

quaint rock
leaden ice
#

Also if you are going to reuse that memory later it's wasteful to clean up the memory just to reallocate it later

quaint rock
#

or making use of arena allocators to clean stuff up on different lifetimes based on what allocator was used

#

pooling has always been a thing used often in games

#

weather that be pooling actual objects that do something or memory

night storm
leaden ice
#

In ECS you could say everything is pooled by default - because all components go in contiguous buffers that get used and reused over and over again

leaden ice
#

generally you'd just let the memory be used by the deactivated bullets

#

it's not an issue

eager tundra
#

memory is cheap

quaint rock
rigid island
#

I'd be more worried shooting 1000 bullets at once, pooling wont help you there

leaden ice
#

You could have an upper limit but if you frequently break that limit and then have to deallocate again then you're essentially operating as if you had no pool at all

quaint rock
#

also its common for a lot of pools to grow as needed

#

then only clear out during a load or something

#

where the GC spike does not matter

leaden ice
#

You would ideally clean up the memory at the point that you are certain you won't need it anymore.

#

Which is extremely bespoke to your game

quaint rock
#

if you could afford taht once you can afford it for the rest of the round or level

night storm
#

hmm alright
but ECS would make it way better i imagine, so the ideal scenario would be to just handle all these bullets with ECS?

brazen nest
quaint rock
#

like i would not choose GO's or ECS based on this alone

#

since there are easy to understand soultions to do what you want in either

brazen nest
quaint rock
rigid island
#

there are rumors future ecs will be created auto into unity from GOs

night storm
quaint rock
quaint rock
steady bobcat
#

e.g. there are different ways to get the current map name in source for client and server and they don't even return the name the same way

quaint rock
rigid island
steady bobcat
rigid island
#

Source Engine was created for specific development from Valve not a general availability engine

quaint rock
rigid island
#

Source 2 is probably very much up to date with features but only they know internally what those are..

steady bobcat
#

well facepunch got it and basically re did half of the engine to be like unity 😆

rigid island
#

Garry is special tho 😄

#

he mind as well be valve

night storm
# quaint rock since there are easy to understand soultions to do what you want in either

alright thanks for the help!
by the way, how does unity handle it when the player is able to go back and forth like in half-life between 2 levels, in unity it would have to create and destroy the scenes repeatedly, if the player goes back and forth a bunch of times and then keeps playing, wouldnt the game keep lagging a lot for a long while due to garbage collector now having to clean up a hundred scenes? each scene containing tens of thousands of objects

quaint rock
#

would pop up loading for a bit

rigid island
#

Unity you can do additive , HL2 does not

quaint rock
#

also there are ways to load in parts of levels at a time

steady bobcat
night storm
quaint rock
#

also it does it already for most of the scene stuff being unloaded

night storm
leaden ice
#

The GC for the most part just does it whenever it thinks it's time. Unloading a scene often would trigger it but not necessarily.

#

it depends

quaint rock
leaden ice
#

You can test all of this yourself btw, run your game with the profiler and see what it does

quaint rock
#

like GC adds little hitches and stuff

#

no one will notice or care about that during a loading screen

night storm
#

yeah its fine during a loading screen, i was just worried that it would start cleaning up the garbage after the loading screen, during gameplay

quaint rock
#

also you keep comparing to hl2 i take it you never played it on release on the type of hardware popular at that time

#

the loads between scenes of larger levels were fairly long and happend often

#

was also a bit of hitching after getting into the new scene

rigid island
#

the game had about 21 years to get optimized the way it is lol

quaint rock
#

also just hardware improving

#

i would worry about making your game

rigid island
#

gotta appreciate valve always dropping updates though to keep up

quaint rock
#

you deal with problems as you hit them and they become important

night storm
#

hmm yeah that makes sense, thanks for the help, i got much smarter with this conversation 😄

night storm
quaint rock
#

experiance will guide you into making better decisions early on, but even then there is still always multiple passes on everything as different things become priority or problems show them selfs

rigid island
#

a turn key solution that works for all is rare if at all existent, each project has its own problems to be solved.

quaint rock
#

it would not be needed in many cases especially around loading anyways

#

for reference i have used it only a handful of times in my whole career

#

since i never had need otherwise

#

since i could solve the problems with other approaches

steady bobcat
#

this is why unity has their incremental gc (its configurable too!)

rigid island
#

You could also have a Loading Scene then Unload/Load each scene additive separate, GC should already kick in now ? (gameobjects get destroyed when scene is unloaded)

quaint rock
#

i have never found GC stutter to be a issue for me even back in unity 4 and 5

#

can be avoided by just putting thought into when things load and unload, and avoiding per frame allocations

chilly surge
#

I think my game allocates ~100 bytes or so every second during gameplay. It used to be 0, but some weird allocations have been showing up since a Unity update that didn't make any sense, so I just chalk it up to editor profiling being weird.

quaint rock
#

profiling the editor is not all that reliable i only bother to profile builds

#

100 bytes every second or so is not going to really hit things hard

chilly surge
#

Yeah I'm fairly certain it's just some editor profiling weirdness, since IIRC it told me it's value tuple constructor that's allocating which makes no sense.

#

But ~100 bytes per second is so low that even if it was real it wouldn't matter anyways.

quaint rock
#

yeah last time i had that, it was a update to our networking lib and it started doing extra logging

#

really find eventaully you just stop thinking about a lot of this and write in a way that is good by default

uneven basalt
#

Guys, how do you learned to code

leaden ice
uneven basalt
#

but, to learn code in unity, c#

leaden ice
#

Once you know one programming language, it's easy to learn others. I was an expert in Java already, and had some C# experience from an internship.

I also took a game dev course in college, though I used Microsoft XNA for that, it's also in C#.

Most of Unity itself I learned through trial and error and self teaching.

#

basically years of trying to make stuff and failing.

#

But slowly building up a corpus of knowledge and experience

uneven basalt
#

But if I dont know anything abt code?

#

where i start

leaden ice
#

It will take you a long time to get good at it.

languid hound
#

Is there a way to force a character controller to recalculate its collisions? I'm using them in a VR game and adjusting the character controller's center and height to match the player's head position, but if a player moves their head into a wall the character controller jitters trying to push itself out

#

However just walking into a wall with the character controller obviously has no jitter

soft shard
# uneven basalt where i start

I would also personally suggest w3schools C# course before starting Unity: https://www.w3schools.com/cs/index.php - it covers all of the basics, in lessons that you can test out like a "code sandbox" for practice - when you get familiar with the basics, you can try to challenge yourself with their examples or look up/create your own, for example instead of just completing the "variable" topic or the "methods" topic, try to make a calculator or some other challenge that uses multiple topics at once - you may either find it trivial or surprisingly very difficult to actually put concepts together despite understanding the concepts independently

When you do become familiar enough with the language that you can do some small challenges with those topics, then I would say is a good time to try to step into Unity Learn Pathways which will teach you how to use the engine and how to use C# within the engine (it wont really teach you C# itself very well, which is why I suggest w3schools and the resource Praetor provided), as Praetor mentioned, it may take a while, but so does learning any skill

inner breach
#

I dont get this? ive used a simple technique to rotate the "weapons" while the player (the square) is holding them where u just take the position of the weapon and the position of the mouse and do some trig to figure out the angle between them. The only problem is that when i do print(transform.rotation.z * Mathf.RadtoDeg); it prints a value that dosent make sense. When i manipulate the objects in the scene rotations work like in the unit circle (the printed value should be 180 or 0 but its 57?), but then the value is different when i print it? I understand if this is a hard question to answer because it might be something with my code but im wondering if anyone has any ideas

somber nacelle
leaden ice
inner breach
#

ohhh i thought a quaternion was just the euler angles but with a w at the end

quaint rock
#

nope if you want to use euler angles with it, you can use AngleAxis, Euler or one of its other helper methods depending on what you need

inner breach
#

thanks so much it fixed my problem

azure egret
#

i have billy and his box collider here, i also have a death animation for billy. do you know how i can get the animation to play and destroy billy after the ghost presses a button in range of the box, ive been trying and i just cant get anything to work.

latent latch
#

Show what you've managed so far

azure egret
#

right now this is all the code together, i deleted all the other stuff because it would cause problems

latent latch
#

Well, I suggest looking up tutorials on how to interactive with other game objects using their colliders. This is usually done using OnTrigger methods using a kinematic rigidbody. You'll find tutorials on how to collect coins, ect using similar logic which is what you'll want to use here to 'press' the button

#

You've also have the option of using raycast/overlap to immediately check locations for colliders.

azure egret
#

Thanks!

wintry monolith
#

Hi there,

I'm having an issue with other objects pushing my character controller even though no rigidbody is attached. Heres the code


using UnityEngine;

public class charMove : MonoBehaviour
{
    private CharacterController characterController;
    public float speed = 5f;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        Vector2 move = new Vector2(Input.GetAxis("Horizontal"), 0);
        characterController.Move(move * Time.deltaTime * speed);
    }
}

latent latch
#

Well, nothing too developed like rigidbody collision, but it provides a simple grounded implementation

night harness
#

I know context is needed for a proper answer but just a curiousity/vibe check from more experienced devs, Do you guys ever run into situations where involving the specific type of a class (outside of direct typechecking/casting) is a reasonable part of a solution or is it pretty much always avoidable

rigid island
azure egret
#

why does c# have to be so difficult this shit doesnt make sense

#

i put 3 lines and i get 7 error messages 💔

somber nacelle
#

#💻┃code-beginner
make sure your !IDE is configured so you don't make basic syntax errors. and maybe also consider learning the basics of the language before attempting to learn unity

tawny elkBOT
dapper schooner
#

anyonje run into this issue when trying to bake Adaptive Probe Volumes

Baking Set-Default.CellProbeOcclusionData.bytes' does not exist

sleek bough
#

@dapper schooner Don't cross-post. And this is unrelated channel.

wintry monolith
wintry monolith
latent latch
# wintry monolith Should I be keeping it enabled?

Not sure what you mean. If you need some semi-created player controller that deals with collisional feedback then use the CharacterController or Rigidbody, otherwise you can always just move them transform in update

low hinge
#

Sounds like you want OnValidate

spark stirrup
#

does anyone know of a way to generate menger sponges with a large iteration count without hitting single digit frames? I want to use it for procedural world gen 😭

spark stirrup
cosmic rain
spark stirrup
spark stirrup
#

the triangle count scales exponentially

cosmic rain
#

Well, one thing that could be a cause is GC pressure. So you really should start with profiling

#

cubeVertices cubeTriangles being created anew for each iteration is a pretty bad thing

#

Beyond that, you should either think of multithreading or compute shaders.

#

Generating it async is an option as well

spark stirrup
#

its not just the generation i'm worried about, its post generation. With 4 itterations I end up with 3.9M triangles

cosmic rain
#

Yeah, if you are going for something like infinite scale, you might want to draw it in a shader with path tracing or something.

spark stirrup
#

it needs collision though, its supposed to be the terrain

cosmic rain
#

or rather ray marching

spark stirrup
#

whats that?

cosmic rain
spark stirrup
#

what if I just had a prefab that changes its itteration count depending on how close the player is to it and then had multple of them kind of creating an LOD effect?

cosmic rain
#

If it doesn't need to be generated procedurally, just generate several LOD versions of the mesh and reuse them

#

Could even do some GPU instancing

spark stirrup
#

that's a good point, i'll experiment with that

spiral crater
#

is using chatgpt ,cursur,deepseek and grok AIs is better for my unity game evrything!!by copy and paste the codes !!?

night harness
#

not using them is the best for your unity game

spiral crater
cosmic rain
#

If you're asking these questions, you probably shouldn't use them yet. Learn the basics, get some experience. When you know what you're doing, you'll know that what tools you can use and how.

spiral crater
cosmic rain
spiral crater
night harness
#

well yeah it would be harder because you would be doing the work

#

learning french is a lot harder than chucking some words into google translate in the same way

spiral crater
cosmic rain
night harness
#

If your too young to learn how to make Unity games then you would be too young to make Unity games

#

This discord won't help you if you use AI generated code

spiral crater
cosmic rain
cosmic rain
tawny elkBOT
#

:teacher: Unity Learn ↗

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

spiral crater
#

@cosmic rain u mean first learn everything about c# then touch your game right!?....and that bot's link will teach me everything about c# and i become a proffesional master!!!?

night harness
#

no one can learn everything

#

you learn a little to do a little

spiral crater
night harness
#

then you learn a little more to do a little more

#

just like in school

spiral crater
#

but this is my first and last game so,,....

night harness
#

your in this server for advice

#

this is the advice

#

if you don't care about the advice

#

¯_(ツ)_/¯

spiral crater
#

how much it had been on unity!?

#

years of experience

#

of you!?

#

so i an take more

#

experience from u !

#

kekwait ?

cosmic rain
spiral crater
cosmic rain
#

To answer your question: it's not too difficult to learn all of these things in a few years. It's just very unlikely that you're gonna be using all of them at the same time. And people tend to forget and get worse at things that they don't do regularly

spiral crater
#

its my first goal then after that my expansion of goals begins!!..

#

i mean after learning this all before i turn 18 ,,btw imma is 14-15 yo rn......after that my own AI

#

is this really better option for my life!?or crazy enough!?

cosmic rain
#

I don't really see the point of such goals. You should probably focus on one thing.

#

If you're only gonna know many things on shallow level you're not gonna reach any success in anything.

spiral crater
#

if i tell u myreal goals...

cosmic rain
#

What for though? I don't get it.

spiral crater
#

is first make a unity game by c# in first 6-8 months then my own link while building my app with that in 1 year then again make a app but by unreal from c++ before 18......

#

u understand!!??

#

sorry a game from unreal...

cosmic rain
#

Not really.
If you keep switching like that you're only gonna create very simple stuff that doesn't have any value.

spiral crater
#

after 18 my own buissness by that all money.........

cosmic rain
#

Or even not finish any project at all. Drop them in the middle.

spiral crater
#

but i never ever give up!!!!

#

NEVER

cosmic rain
spiral crater
#

give up wasnt even a thing'

spiral crater
cosmic rain
#

Okay, at this point I feel like you're just trolling.

Anyways, this is not the right channel for such conversations. Do you have an actual question related to coding in unity?

spiral crater
#

can u please tell me whatshouldi really do

cosmic rain
#

For me these goals sound unrealistic. At least not in the time range that you specified. And it's still not clear what your actual end goal is.
And I'm sure most people here would agree with me.

#

Anyways, this is not the correct channel for such topics. At the very least move to #💻┃unity-talk

spark stirrup
spiral crater
#

anyways the time and me will decide by my work

#

more rest is not equal to dream,,,,less rest and more work= execution!!!

wintry monolith
wintry monolith
dawn nebula
#

I'm trying to write a script that feeds in some information into a SpriteRenderer's UV1.

        float minU = 1;
        float maxU = 0;
        float minV = 1;
        float maxV = 0;

        foreach (var uv in spriteRenderer.sprite.uv)
        {
            minU = Mathf.Min(uv.x, minU);
            maxU = Mathf.Max(uv.x, maxU);
            minV = Mathf.Min(uv.y, minV);
            maxV = Mathf.Max(uv.y, maxV);
        }

        var uv1 = new NativeArray<Vector2>(spriteRenderer.sprite.uv.Length, Allocator.Temp);
        for (var i = 0; i < uv1.Length; i++)
        {
            var uvactu = spriteRenderer.sprite.uv[i];
            var u1 = Mathf.InverseLerp(minU, maxU, uvactu.x);
            var v1 = Mathf.InverseLerp(minV, maxV, uvactu.y);
            uv1[i] = new Vector2(u1, v1);
        }
        spriteRenderer.sprite.SetVertexAttribute(VertexAttribute.TexCoord1, uv1);

What do I need to do to make it so this code runs whenever the SpriteRenderer readies a new sprite? This includes in the Editor. Like whenever a new sprite is set.

astral nexus
#

It's more of an architectural question rather than specific to general scripting in Unity, but what is the way of storing RUNTIME data between components in modular architecture with heavy composition use?
For configs/static data it's easy - just use SOs or/and JSON serialization, but what about runtime data which changes all the time? I feel like I'm fighting Unity with this, because I don't want to store data and logic in MonoBehaviours and want to separate them. Any tips on this?

rigid island
lean sail
coral bluff
#
void Move(int Ground)
{
    if (!isChargingJump && !justJumped)
    {
        float targetSpeed = moveInput * moveSpeed; // Maksymalna prędkość
        float currentSpeed = rb.linearVelocity.x; // Aktualna prędkość
        if (Ground == 1) // Normalna ziemia
        {
            if (moveInput != 0)
            {
                currentSpeed = targetSpeed;
            }
            else
            {
                currentSpeed = Mathf.Lerp(currentSpeed, 0, Time.fixedDeltaTime * 2f); // Wolniejsza zmiana prędkości
            }
        }
        else if (Ground == 2) // Śliska ziemia
        {
            currentSpeed = Mathf.Lerp(currentSpeed, targetSpeed, Time.fixedDeltaTime * 0.2f); // Wolniejsza zmiana prędkości
        }

        rb.linearVelocity = new Vector2(currentSpeed, rb.linearVelocity.y);
    }
}

Can anyone help me.

Okay so there is situation, that player checks ground under him, and ground == 1 is normal, a lot of friction and ground == 2 is slippery, idk 0.7 friction so it's like ice

And i want for my character to slowly gain speed, like in jump king on ice, but i cant do it. Can anyone help me?
I have been trying to change this for a few hours already

mellow sigil
#

Use AddForce instead of directly setting the velocity and that's what you get automatically

worldly stirrup
#

I have a variant of a menu template that I changed to be a pause menu, but when I press the "pause" button, the menu doesn't pop up and I get a "NullReferenceObject"

#
{
    [Header ("General Values And References")]
    public GameObject pauseMenu;
    
    void Start()
    {
        closeMenu(pauseMenu);
    }

    void Update()
    {
        handlePause();
    }

    private void handlePause(){
        if(inputManager.instance.pauseOpen){
            if(!pauseManager.instance.isPaused){
                setSelectedFirst(pauseManager.instance.transform.GetChild(0).GetChild(0).gameObject);
                pauseManager.instance.setPause(true,0,"Menu");
                openMenu(pauseMenu);
            }
        } else if(inputManager.instance.pauseClose){
            if(pauseManager.instance.isPaused){
                resumeGame();
            }
        }
    }```
#
{
    [Header ("Pause Instance")]
    public static pauseManager instance;
    public bool isPaused;

    void Awake()
    {
        if(instance==null) instance=this;
    }

    public void setPause(bool paused, float time, String action){
        isPaused=paused;
        Time.timeScale=time;
        inputManager.player.SwitchCurrentActionMap(action);
    }
}```
winter bramble
#

has anyone experienced a 1px border around Canvas screen space overlay? It seems to be present on all Unity 6 URP setups.

#

I have the canvas setup to stretch full, ive played with all the settings. Nothing fixes it.

night storm
winter bramble
mellow sigil
#

You'll have to tell which line throws the error, to start with

worldly stirrup
#

I tried creating the menu an instantiated object but it calls an error when I try to close it with the "resume" button in the menu

#
        pauseManage.setPause(false,1,"Player");
        closeMenu(pauseMenu);
    }```
mellow sigil
#

Do you have an active pause manager object in the same scene?

worldly stirrup
#

Yeah

#

When I press on the escape key, the pause menu pops up which has the manager script, but when I try to close it with the "resume" button on the menu, it causes a null error

mellow sigil
#

Is this now a different problem?

worldly stirrup
#

I first want to know why it doesn't work without an instantiate

#

A static instance is working with my input manager, that is always active

#

Here however, I can't set the pause menu as active or inactive

mellow sigil
#

Turn on error pause in the console and show a screenshot of the editor window with the pause manager selected when it errors on pause button

mellow sigil
#

That's a different error

worldly stirrup
#

This is without the instantiate

#

I still don't know what causes it

somber tapir
lilac frigate
#

How does a armour system work with a character mesh? like how does armour models get applied how would you model the armour etc
Or a skin system

halcyon steppe
#

Hi, is there any simple way to read what key the user last pressed or do I have to go through and manually cover all options the user can press?

thin pecan
#

is there a way to like script if smth touches you the game kicks u out

soft shard
halcyon steppe
somber nacelle
somber nacelle
halcyon steppe
somber nacelle
#

I was kind of hoping there was a variable that automatically saves the last key that was pressed
you'll have to make that yourself which is what i suggested

halcyon steppe
#

Oh well… thank you for the help, I shall get coding then

thin pecan
#

btw what i mean by kick not a hit but to make the game close

somber nacelle
#

so now you can google "how to close game" or whatever

thin pecan
#

i will just cancel this idea cuz u cant rlly do it (you can im stupid)

#

lemme make escape key close the game

somber nacelle
#

if you'd bother actually researching you'd find it is incredibly simple to do this

thin pecan
#

wait im stupid

somber nacelle
#

great! so instead of using a button, you quit in the collision detection

#

it's literally that simple

thin pecan
#

im hella stupid for no reason

#

or actuacctly im lazy lemme use my brain next time thanks ♥

civic girder
#

How do I add a generic extension method?

I'm trying to create a utility method for all my list classes but it doesn't seem to work:

public static class CollectionExtensions
{
    public static void PrintList(this List<T> list)
    {

    }
}
somber nacelle
#

you need a generic type parameter on the method

civic girder
#

that would mean I need to define a function for every possible type?

somber nacelle
#

no, that would mean you need a generic type parameter on the method declaration

#

T does not exist in this context because neither the method nor the class are generic

civic girder
#

so like this?

    public static void PrintList<T>(this List<T> list)
soft shard
# halcyon steppe So checking for each possible input manually is best then? I was kind of hoping ...

Sadly, the old input system is fairly "minimal" and doesnt have a lot of features built into it, so with it you would have to create a lot of your own systems, the only thing that system has for "saving the last input" is the ascii you were already using, you could pair that with maybe checking for "modifier keys" (being things like control, alt, shift, etc), that way you dont have to cover EVERY key (or maybe you could convert the KeyCode enum into an array and loop through GetKey calls)

lyric veldt
#

https://paste.mod.gg/zpqydplisqwo/0
Does anyone know how to make the player slowly slide along a wall when colliding with it? For example, in most games, if there's a wall on the left or right side of the player and the player presses W A or W D, they still move forward slowly while sliding along the wall. Right now, my movement system just completely stops the player if they're colliding with anything or if their movement isn't perfectly straight along the wall.

leaden ice
#

Maybe it's a friction problem?

lyric veldt
#

let me see

#

yeah idk

lyric veldt
#

it turned out

#

i just needed a physics material on my player

sullen urchin
#

guys what’s a must-have plugin for Unity in VS?
Any recommendations?

rigid island
worldly stirrup
#

It is a prefab too

somber nacelle
#

it's also in the scene

worldly stirrup
somber nacelle
#

at this point you need to show your code because it's impossible to guess what is actually happening

worldly stirrup
somber nacelle
#

i'm not watching a video to see code. if you have !code then share it correctly 👇

tawny elkBOT
somber nacelle
#

god so many singletons. what line is the error occurring on

#

share all of the code because i'm really not about to start playing 20 questions to get all of the context

worldly stirrup
#

Actually screw this, Ill just make it an instantiate

sly helm
#

I don’t know why I’m getting a not defined error

#

It keeps telling it it doesn’t exist in current context

cosmic rain
#

We don't have the ability to read your mind or see your monitor/code/error through space and time.

floral flame
#

I'm making a bullet hell boss and I don't yet have a system for managing attacks. In fact, I don't know how to define an attack yet.

I know what an attack will be: spawning certain prefabs at certain timings.

I know what the attack manager should do:
Attack management system

  • Decides what attacks to do.
  • Needs to react to various events, such as the player entering an area or boss HP falling below a threshold.
  • Needs to be able to track what attack is currently happening.
  • Needs to be able to cancel ongoing attacks in response to these events.
  • Attacks will need to control various prefabs.
  • As reusable and flexible as possible.
#

Also is there some way to create reusable components you can mix and match to create custom entities?

#

My best idea is using scripts

tame lance
#

So Im working on a generic asset loader for an old game (Im modifying assembly, the game is long dead and Im currently forced to work with the 2018 unity APIs it was built with), and Ive added a bunch of classes to it so far.

Currently everything functions as intended, the asset files are valid, all the paths are correct, and Im sending the right information to the Asset Loader, but when I start the coroutine, nothing happens.

The asset loader is attached.

The last thing I see ingame after running TestConvertFirstSong is a debug output ingame of the fixed path. The path displayed ingame is correct.

The first debug log inside the LoadAudioFile function never even shows up... So I assume Ive built the IEnumerator incorrectly / am using coroutines wrong?

#

(What I see ingame after running that test function).. Never even logs after the fixed path

vestal arch
tame lance
#

Im not asking for help with modding.

#

This is just a basic piece of code (That I wrote)

#

What I do with the code isnt really anyones business is it?

vestal arch
#

it is to mods tbh

tame lance
#

Im just asking for support with a generic coroutine... I didnt ask for someone to minimod

vestal arch
#

if you read #📖┃code-of-conduct, you'll see that community members are also expected to help remind people of stuff there

tame lance
#

No one likes a minimod

#

Just saying

vestal arch
#

yeah sure whatever

#

the coroutine looks correct
you probably don't need the yield break; but i don't think it's related to not getting that log

tame lance
#

Compiler just automatically places it there unfortunately.

#

It does that with a lot of stuff actually, I write code but it changes it as it pleases

#

Luckily its mostly just Efficiency stuff

#

It doesnt really break anything

vestal arch
#

i mean it is kinda implicit at the end of the enumerator anyways

cosmic rain
vestal arch
#

maybe try a different yieldinstruction to test, just yield return null; or yield return new WaitForSeconds(1);

cosmic rain
#

To confirm that print something right after the yield

tame lance
#

Unless coroutines just inherently dont get caught in the same way

#

No idea

vestal arch
#

it may be an issue with the usage of WWW

Notes http://, https:// and file:// protocols are supported on iPhone. ftp:// protocol support is limited to anonymous downloads only. Other protocols are not supported.

Note: When using file protocol on Windows and Windows Store Apps for accessing local files, you have to specify file:/// (with three slashes).

#

other platforms aren't mentioned

cosmic rain
#

Anyways, logging right after the yield should provide some clues

tame lance
vestal arch
tame lance
#

So either it cant log in the context of the coroutine, or the coroutine just isnt activating for some reason

#

¯_(ツ)_/¯

cosmic rain
vestal arch
#

they're slightly different

cosmic rain
#

Aah, I see. That's confusing

tame lance
#

Yeahhh

#

This log works great

#

The one that logs the same path in the start of the coroutine isnt logging

cosmic rain
#

This might actually be a modding thing.

tame lance
#

Now, it could be an issue with my shoddy logging system, Ive had weirder issues

#

But theres no other way to get realtime debugging afaik

cosmic rain
#

This should work perfectly fine in a normal project

cosmic rain
tame lance
cosmic rain
#

Which you should, seeing that you're modifying code and supposedly compile it

cosmic rain
#

It's not modding/decompiling related.

tame lance
#

Oh then Im unaware of how to do it. In theory though the logs should have everything sent ingame

#

its just a pain to work with

#

closing and opening the game, constantly reloading the text files lol

cosmic rain
#

Learn how to use the visual studio debugger.

#

This is making a lot of assumptions on the game that you're modding and the modding workflow though, so you should probably move to the game modding community.

tame lance
#

Im mostly just doing this for a friend whos maintaining this old game / building a private server for it

cosmic rain
#

No. I don't even know what game it is.

tame lance
#

Oh I thought you meant a general unity modding community

#

nvm then

cosmic rain
#

There's no such community. Or I don't know about it.

#

Every game modding workflow would be unique and different depending on what the game allows.

tame lance
#

Well I guess there could be other ways to prove the coroutine is running, if my logger might be the cause of my confusion...

#

Is there a way to tell when the coroutine is finished outside of the context of the IEnumerator

cosmic rain
#

My guess is that you're injecting the code or something. That might fail on many levels with more advanced features like coroutines.

tame lance
#

All of my code runs in the same context as the original

#

It should behave as normal / have access to all the same libraries and systems, .NET or otherwise

cosmic rain
#

That's not the point. The point is that it's probably bypassing the normal unity compilation pipeline, possbily missing some steps, like codegen and such that could be required for coroutines to work(all assumptions).

tame lance
#

Possibly, I had that concern too, but when I looked at the compiled code for other MonoBehaviors / coroutines, it matched mine

#

All it does outside of the editor is convert StartCoroutines to base.StartCoroutine and it adds yield break; at the end of functions that didnt declare it literally

#

Atleast as far as I can tell

#

The rest of it matches the unity API standard

#

Im assuming that, since theres no errors, theres a likely chance that the coroutines ARE working

#

Im just unable to log from the context of inside the IEnumerator

#

¯_(ツ)_/¯

#

In which case debugging will be slightly more annoying, but not impossible

tame lance
#

Definitely a null reference there

#

Now what that means? No idea

#

I guess the most obvious option is that it cant see the loadaudiofile function

#

though that doesnt really make sense

#

DnSpy seems to detect it as a safe reference

oblique spoke
#

This seems to be mostly about modding. Please use a different server for modding activities.

tame lance
#

Im trying to fix a coroutine?

#

What about this is modding specific

quaint rock
#

there is not much to think about with coroutines, its like are you yielding correctly and is the coroutine running on a enabled object

tame lance
#

Does it require I create an empty to attach it to ingame?

quaint rock
#

yes it requires a fully working MB to run on

tame lance
#

thats probably the issue then.

quaint rock
#

that is on a game object that is active

#

also what do you mean defined like a normal class?

#

MB's should never be created with new

#

if you need to add one at runtime use AddComponent<T>()

tame lance
#

Works fine for everything else ive done

#

but Ive never tried it with monobehaviors

#

So this is a bit of a first for me frankly

quaint rock
#

this is pretty basic unity 101 stuff

tame lance
#

To be fair, I made like one game with unity some 6 years ago 💀

#

I havent touched it since hah

quaint rock
#

but MonoBehaviors only properly work if they have a instance on a GameObject

tame lance
#

Gotcha... Should just be fine if I add the script to an empty and instantiate it during runtime?

#

Or can they not be handled like that during runtime

quaint rock
#

otherwise they do not receive any of the messages from unity like Update

tame lance
quaint rock
#

they can be added to GO's just fine at edit time or runtime

tame lance
#

Alrighty, Ill give that a try

quaint rock
#

though like proper workflow you know is to just add them in the editor

vestal arch
quaint rock
#

but yeah 100% sounds like they are trying to mod a game without understanding unity enough to do so

tame lance
quaint rock
#

and using that is a entry to unity is going to be a rough time concept wise

tame lance
#

Eh, not the worst thing Ive ever had to learn.

#

Ive always been self-taught when it comes to code lol

#

It has its problems, but I work with it

quaint rock
#

i am not commenting about self learning code like most people do that

tame lance
#

So Im not sure what youre talking about lol

vestal arch
tame lance
#

Bruh... what... what kind of mental gymnastics is that

vestal arch
#

"monobehaviour not a gameobject" is not a normal unity situation/issue

tame lance
vestal arch
#

it isn't

tame lance
#

:/

vestal arch
#

so... that's kinda speaking to your inexperience with unity?

tame lance
#

Sounds to me like youre just trying to justify not giving someone support for no reason other then feeling self-righteous..

vestal arch
#

components just don't exist outside of gameobjects in the proper context of unity

tame lance
#

If you dont wanna interact... just dont

#

Like I dont know what else to tell you

vestal arch
#

your issue arose specifically from modding; modding-focused communities would be much more well-suited to help you

quaint rock
#

modding is not on topic for the server

tame lance
#

Like if I didnt even mention it to you guys you wouldnt even be fussing

quaint rock
#

and the relationship of components to gameobjects is literally impossible information to avoid

tame lance
vestal arch
oblique spoke
vestal arch
#

you don't manually attach scripts to gameobjects as a separate step

#

you create scripts directly on gameobjects

#

that's just how unity works

tame lance
#

Youre genuinely one of the most toxic people Ive been forced to interact with on here... Why are you so obsessed with trying to invalidate a discussion.

oblique spoke
#

Because it's against the rules. Let's stop this here.

tame lance
#

Cant imagine how you guys treat people new to unity if this is the norm

vestal arch
#

i tried to warn you shrugsinjapanese

#

you asked for a mod opinion and got a mod opinion, what else do you want lol

quaint rock
#

@vestal arch no need to comment more and prolong this, its handled

tame lance
#

It took a sec to realize I couldnt instantiate directly since the startup code isnt even run from a monobehavior, but I got it working

quaint rock
quaint rock
cosmic rain
tame lance
#

It only runs once on startup just to load some files and stuff and convert them to specific asset types like audioclips and whatnot

#

(editing assets is a hellhole Im not climbing down)

tame lance
#

I just had a basic error because, unfortunately, Ive never really worked with unity in a serious manner

#

atleast not in many years

#

so Ive forgotten a lot of the basics

#

use it or lose it, as they say

cosmic rain
#

Just saying, if you're going somewhere, adhere to their rules. That's true to everything in life.

azure forum
#

Any downside is writing my custon .lang file type for handling localization instead of using json? i think that a custom file type would be easier to write, like
cards.cardEffects.basicDamage=Deal 2 damage

instead of messing with brackets etc...

wicked scroll
vestal arch
#

you could always use some other existing format, like yaml or ini or toml

chilly surge
#

Depends a lot on your workflow. If you are going to translate by actually modifying the file by hand, then sure. But if you want to integrate the workflow into some translation platforms, then you should not worry about what the file looks like and instead look at what's supported.

quaint rock
#

feel like i would just use a established format that way i do not waste time on sorting out how to parse multiline strings or escaping stuff

#

json you likly already got deserilaizer for, and TOML is a good choice for a easier to human edit thing

tame lance
#

Anyone know what formats WWW accepts for audio files? It has a GetAudioClip() function but it seems to always throw a null reference exception when I use it, whether its .wav / .m4a / .mp3.

Ive verified www works, the bytesDownloaded reads ~14mb, which is the size of the audio file

leaden ice
#

Also you should be using UnityWebRequestMultimedia generally

#

WWW is deprecated

tame lance
vestal arch
tame lance
#

I was missing the exact AudioType optional parameter I just noticed

#

so ill try setting that

#

It may just be failing to read the extension or something

leaden ice
#

Says right there in the doc

vestal arch
tame lance
tame lance
vestal arch
tame lance
# leaden ice then back to https://discord.com/channels/489222168727519232/763495187787677697/...

Error: System.NullReferenceException: Object reference not set to an instance of an object at ExternalAssetLoader<LoadAudioFile>

    public IEnumerator LoadAudioFile(FileInfo file)
    {
        string url = string.Format("file:///{0}", file.FullName.ToString());
        TheGreatDebugMenu.QuickLog("Loading File", url);
        WWW www = new WWW(url);
        yield return www;
        try
        {
            TheGreatDebugMenu.QuickLog("Loaded Data", www.bytesDownloaded.ToString());
            this.clips.Add(www.GetAudioClip(false, false, AudioType.WAV)); // Problematic Line
            yield break;
        }
        catch (Exception err)
        {
            TheGreatDebugMenu.QuickLog("Asset Loading Failed!", err.ToString());
            yield break;
        }
        yield break;
    }

It doesnt say what line for some reason but its being caused by the one I commented on

steady bobcat
#

unity 2018?? fuck thats old

tame lance
#

Oh shit I bet I didnt give it a default value on Start

#

fuck

wicked scroll
#

what an awful emoji

tame lance
#

Should work... hopefully

#

Ima cry if it dont

#

HELL YEAH.

#

Finally

#

no errors!

faint tree
#

anyone tried latest unity/ .47f1, somehow rigid bodies are VERY slow here, bring my game to less than 1fps

sage fern
#

guys how do I work with tilesets in unity? All I found seems rather outdated, there has got to be a proper workflow

#

I dont want to create yet another custom tool just to automatically create tile rules...

sleek bough
tawny elkBOT
#

:teacher: Unity Learn ↗

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

whole ravine
#

Is it possible to connect the Skylanders portal to Unity and read and write innit ?

naive swallow
#

From what I remember, it's literally just an NFC reader

wicked mountain
#

Bring back skylanders!! 🔥🔥

naive swallow
#

But I don't know if you can do anything like activate the lights and whatnot on it without reverse-engineering some sort of driver

#

But you can probably get your computer to recognize it as an NFC reader with enough shenanigannery

steady bobcat
#

i wouldnt be suprised if something already exists and if it has exported c functions then you can use it

naive swallow
#

Yeah, modders are pretty good about making those old quirky hardware experiments survive well past end of life

#

The Xbox 360 Kinect is still the best consumer-grade 3D-motion tracking device ever released

shadow cradle
#

anyone knows how to make a serialized dict work? everytime i try to add a value or key i get ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

low hinge
#

You need a class for it

#

Lemme find mine

#
public abstract class UnitySerializedDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver {
        [SerializeField] private List<KeyValueData> keyValueData = new();

        public void OnBeforeSerialize() {
            keyValueData.Clear();
            foreach (var kvp in this) {
                keyValueData.Add(
                    new KeyValueData() {
                        key = kvp.Key,
                        value = kvp.Value
                    });
            }
        }

        public void OnAfterDeserialize() {
            Clear();
            foreach (var item in keyValueData) {
                this[item.key] = item.value;
            }
        }

        [Serializable]
        private struct KeyValueData {
            public TKey key;
            public TValue value;
        }
    }

Then define a dictionary using something like this

[Serializable] public class TypeObjectDictionary : UnitySerializedDictionary<Type, object> {}```

then use that type as your dictionary
shadow cradle
low hinge
#

Unity doesn't have a serializable dictionary afaik

reef garnet
low hinge
#

This dictionary is Odin inspectable btw, looks really nice with Odin installed

shadow cradle
#

Dunno if thats the one i used cause im not on pc rn. It shows two lists in the inspector but cant add stuff in them

low hinge
#

Didn't know about that one. Show us the code you used to cause the error when you get to your PC

#

Actually this isn't Unity's, just looks like it made its way into the docs

Unity can't serialize Dictionary so here's a custom wrapper that does. Note that you have to extend it before it can be serialized as Unity won't serialized generic-based types either.

lyric steppe
#

Hey, I am trying to do a DevLog, BUT when I when I switch to a version before the newest they will overlap. For example when I switch to a scene where the obj didn't exist before they exist there now but there Prefab is not in the Project folder. All the Project files are chainging but the scene is not. Why?

low hinge
#

Sounds like you're modifying prefab files instead of instantiating and modifying them to me

lyric steppe
#

After:

leaden ice
#

You sure those are even the same scene?

vestal arch
#

also that "before" has an unsaved samplescene thonk

lyric steppe
#

yeah 100% same scene but In the second photo I switched to an older changeset and back

lyric steppe
#

I found out that the obj in the scene is only changing when I switch to a specific changeset

shadow cradle
low hinge
#

Interesting

shadow cradle
#

extending didnt work

low hinge
#

Show the code causing the error

safe fable
#

weird question. not so much code related but Unity. When i start my game my computer literally starts screeching and making weird noises LMFAO. NO idea why and it only happens when i open my project, no other game. no one would happen to know why, would they? I don't even know where to begin to know what is causing it or if its even an issue lol

leaden ice
#

try limiting your framerate by turning on vSync or setting a max framerate

#

e.g. Application.targetFrameRate = 60;

safe fable
#

thats probably 100% it i think you're right

#

ill test it out

safe fable
wicked mountain
leaden ice
safe fable
#

okay bet, sounds good

shadow cradle
reef garnet
#

general physics question, how could I factor linear damping into applying a force to ignore the damping in that specific direction, a bit lazy to deal with adding my own counter forces so wanted to try utilizing linearDamping

safe fable
#

@leaden ice yeah, that was definitely the issue using vsync and limiting the frames fixed it. It also fixed the issue where my VFX / particles were moving at lightning speed in the build while in the editor they looked fine. Maybe i just keep players framerates capped 🤷‍♂️

reef garnet
#

I am using rb.addForce for my movement if that helps

hexed pecan
#

Use the angle or dot product between your velocity and that specific direction. Then modify linearDamping based on that value.

wicked mountain
#

hold on- I actually use a 3rd party one by AYellowPaper

#

works out of the box just fine

#

example usage

shadow cradle
leaden ice
#

Which you need to fix separately

shadow cradle
wicked mountain
shadow cradle
#

meh u gotta put the whole thing in his namespace

somber tapir
shadow cradle
#

tried didnt recognize it

shadow cradle
wicked mountain
#

I didnt have the edit the code at all

#

I just used it like this:
[SerializedDictionary("Name", "Stat")] public SerializedDictionary<string, Stat> stats = new();

somber tapir
somber tapir
wicked mountain
#

You installed it from the asset store?

last island
#

I must be missing something about how packages work in Unity 6. I have included a newtonsoft json package by adding it manually.
But I can't seem to call Newtonsoft other than as a Unity.Plastic package??

somber tapir
last island
#

No, this is a package I added with com.unity.nuget.newtonsoft-json in Unity

#

Using this option

quartz folio
#

Yes but is your code under your own Assembly Definition? Or does VS say your assembly is Assembly-CSharp?

last island
#

The latter.

brazen nest
#
        turretList = new List<GameObject>();
        enemyList = new List<GameObject>();
        projectile1List = new List<GameObject>();
        projectile2List = new List<GameObject>();
        projectile3List = new List<GameObject>();
        projectile4List = new List<GameObject>();
        barrier1List = new List<GameObject>();      
        barrier2List = new List<GameObject>();
        barrier3List = new List<GameObject>();  
    }``` need someone smart to give me some advice on how to create a ton of specific objects for each one of these lists, trying out object pooling
#

i could use a for loop for all of them and add onto them but i feel like there's an easier way

#

or well, simpler

quartz folio
# last island The latter.

If it's not, then try regenerating the project via Preferences/External Tools in Unity, and restart VS

last island
#

Alright

quartz folio
#

And make sure you have no compiler errors

last island
#

Yeah I'm suspecting perhaps compiler errors made the package simply not compile or something

#

I'll try those things

#

Okay took a few tries. Had to remove the package from Unity, re-add it and then regenerate @quartz folio
Thanks

shadow cradle
shadow cradle
somber tapir
brazen nest
#

because some of them have Deployable script, some have Projectile, I dont have a specific script for each one, therefore their type is GameObject

naive swallow
#

You should make the list of that type

brazen nest
#

seems like the same thing

naive swallow
#

A reference to the component you actually want lets you access all of the things in that script

brazen nest
#

Oh, well I just need a reference to the GameObject, because this is for Object Pooling, disabling and enaaabling the object

#

thats all

naive swallow
#

And you can always get the GameObject a script is attached to with .gameObject, but getting a component requires GetComponent which is slow

brazen nest
#

I guess Ill just write a for loop for the lists lolo

#
        turretList = new List<GameObject>();
        enemyList = new List<GameObject>();
        projectile1List = new List<GameObject>();
        projectile2List = new List<GameObject>();
        projectile3List = new List<GameObject>();
        projectile4List = new List<GameObject>();
        barrier1List = new List<GameObject>();      
        barrier2List = new List<GameObject>();
        barrier3List = new List<GameObject>();

        // Initalize all objects into lists
        // turrets
        for (int i=0;i<turretListSize;i++){
            GameObject newObject = Instantiate(turret);
            newObject.SetActive(false);
            turretList.Add(newObject);
        }
        // enemies
        for (int i=0;i<enemyListSize;i++){
            GameObject newObject = Instantiate(enemy);
            newObject.SetActive(false);
            enemyList.Add(newObject);
        }        
    }``` ended up just doing for loops lol, like this
lean sail
# brazen nest ``` void Awake(){ turretList = new List<GameObject>(); enemyL...

you should really just rewrite this all, especially so you dont have list1 2 3 4 for everything you do. this is going to be awful for you in the future.
Even if you were to continue like this, surely with all the repeated code you couldve just made a method

void PopulateList(List<GameObject> listToFill, GameObject prefab, int count)
...
brazen nest
lean sail
brazen nest
barren sedge
#

How can I make googly eyes? I tried using edge colliders and rigid bodies but that didn't work. The googly eyes push against the player and they can also clip through the eyes themself

cosmic rain
#

That's something out of nightmares.

#

On the topic though, you have several problems that you need to solve:

  • both(?) the eyes and the body needing to be controlled by physics means that they would collide and affect each other. Maybe you can consider hardcoding the eyes behavior instead of letting physics control them.
  • since the eyes are controlled by physics, they collide with the character collider, causing an outwards force. Perhaps you could place them on separate layers that don't interact?

Overall, I'd consider not using physics for the eyes.

thin pecan
#

it maybe be linearvelocity but idk

barren sedge
#

rigid bodies apply delta time automatically

#

so you can omit that

thin pecan
#

oh lol i didnt know that

barren sedge
#

yeah it'll make the bullets go much slower

thin pecan
#

uhh it doesnt work still

#

idk why it stays up like that

barren sedge
#

you make it look up

thin pecan
barren sedge
#

Vector3.up = (0, 1, 0) iirc

thin pecan
#

💀

#

im stupid

#

u are right the position is fixed

#

but idk why it doesnt fire

#

like it stays

iron vigil
#

does anyone know how to stop the Player camera from clipping and seeing through walls "im in first person"

modern atlas
modern atlas
vague cosmos
#

Can someone help me out here? I'm messing with online right now using netcode for entities (this guide: https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/build-with-netcode-for-entities), but the player prefab does not work correctly. The one in the air with no gravity is the online player, and the one on the bottom is the offline character, how it should work. I'm not really sure how the online works, so i'm having a hard time figuring out what the problem is. Any help is appreciated!

rigid island
vague cosmos
#

Oh perfect, thanks!

fresh sandal
#

Hey guys, I'm trying to write a script that hides the back of the walls when they are facing my camera, so I can have a full view of the room every time.
I'm not sure what is wrong, because sometimes I still can see the back of the walls. Any idea on how to do it?

fresh sandal
# vague cosmos Oh perfect, thanks!

This is my curent iteration of the code:

using UnityEngine;

public class WallAutoToggle : MonoBehaviour
{
    public float threshold = -0.5f; // Hide when the camera is looking at the wall's back
    public Transform cameraTransform;

    private bool isHidden = false;
    private Renderer[] renderers;

    void Start()
    {
        if (cameraTransform == null)
        {
            if (Camera.main != null)
                cameraTransform = Camera.main.transform;
            else
            {
                Debug.LogWarning("WallAutoToggle: No Main Camera found! Assign cameraTransform manually.");
                enabled = false;
                return;
            }
        }

        renderers = GetComponentsInChildren<Renderer>();
    }

    void Update()
    {
        if (cameraTransform == null) return;

        // Direction from wall to camera
        Vector3 toCamera = (cameraTransform.position - transform.position).normalized;

        // Compare wall forward to direction to camera
        float dot = Vector3.Dot(transform.forward, toCamera);

        bool shouldHide = dot < threshold;

        if (shouldHide && !isHidden)
        {
            SetRenderersVisible(false);
            isHidden = true;
        }
        else if (!shouldHide && isHidden)
        {
            SetRenderersVisible(true);
            isHidden = false;
        }
    }

    void SetRenderersVisible(bool visible)
    {
        foreach (var rend in renderers)
        {
            if (rend != null)
                rend.enabled = visible;
        }
    }
}

vague cosmos
fresh sandal
#

Oh sorry bro

#

my bad

#

Didn't mean to

fresh sandal
#

Ideally I want somehthing like, "if any point of the back of the wall is visible, hide it"

sterile reef
dense coral
#

Code design question

I have inventory in my game. I want to have items in it with whatever associated functionality.
I also want my code to be modular: modules not being dependant on anything not strictly related to it.
There are these classes already:
Module 1: Inventory InventorySlot InventoryItem
Module 2: InventroyUI InventorySlotUI InventoryItemUI -> dependant on the above by design.
Module 3: PlayerInventoryController -> dependant on Inventory by design (takes input and selects InventorySlot)

But lets say i want some items that have some special effect displayed every frame they are selected.
I would create something like PreviewItem class. But how do i structure my code to include/use it?
I dont want to just include a reference to it to InventoryItem because it doesn't relate to inventory module. What if in the next game i dont want any preview? I would have to crop the code. If i leave the field empty it still feels wrong: imagine i had 50 distinct item functionalities. If i include everything as InventoryItem field it becomes unclear which ones actually need to be filled for inventory system to function.

sterile reef
latent latch
sterile reef
# sterile reef You can use an interface to add functionality without adding useless references....

Example1:

{
      Public void Effect() { // spin or something }
// every item does this now

}```
Now you can access Effect by getting the interface as a component.

Example2: 
``` public class Fruit: Item, IinvPreview // inheritance from a generic item class
{
      Public void effect() { // explode }
// now every fruit type will explode when called

}```
If the InventoryItem has a reference to a generic item class you can getcomponent<IinvPreview> to all the Effect method
dense coral
sterile reef
#

Uhh make an scriptable object with the method and other stuff you want the item to do and have a list with those scriptable objects in InventoryItem.

#

Could be a solution

dense coral
indigo frost
#

is it possible to export the texture from a material, if the texture isnt readable?

indigo frost
#

Yeah, but i need to Export it, as in to a file

#

Because a fonts Materials MainTexture is black, and i wanted to make it White.

sterile reef
#

theres an imageconversion module

#

this should help you out

indigo frost
#

Thanks!

zealous lava
#

Hi

#

Anyone controlls A* for pathfinding 2d?

young yacht
# thin pecan

you can use Translate instead, something like

void Update()
    {
        transform.Translate(Vector3.forward * bulletSpeed * Time.deltaTime);
        Destroy(gameObject, 3f);
    }
hexed pecan
zealous lava
vestal arch
astral sky
#

<i>Autoconnected Player "Autoconnected Player"</i> StackOverflowException: The requested operation caused a stack overflow.

I'm trying to run a test but I can't as the player instantly gets shutdown after building due to a stack overflow exception, I cannot find anywhere any log about what might be causing this

thick terrace
astral sky
#

There's too many logging options, do you mean Preferences > Scriptable Build Pipeline > Use Detailed Build Log?

thick terrace
#

the one in player settings, you can also change it in the menu on the console view in editor:

cosmic rain
astral sky
#

Hold on, I'm trying to rerun it and I'm no longer getting the stack overflow message but the player is still getting disconnected

#

I'm just not getting anything now, the disconnect message says nothing and the test runner is permanently hung on "wait for player run"

cosmic rain
astral sky
#

Linux

#

In fact I don't have any other platform other than Linux

cosmic rain
#

That might be complicated then... I don't think there are many devs here that worked with unity on Linux. Definitely not me.

astral sky
#

Absolutely did not happen yesterday at the very least so I'm extremely confused, I just changed the code in my test

kind river
#

Solved, I was looking how to get a Tile color. I dismissed Tilemap.GetColor as I was expecting it to return the color of the Tilemap. Turns out it takes a Vector3Int in and output the color of the Tile at that position

fresh sandal
wintry crescent
#

I have this bit of code inside Update() Is it really allocating 3 Vector2s every update, even if it's the same values every time? Or does it get optimised away by the compiler? Do I need to painstakingly check every single value, to determine if it needs updating?

Please ignore the variable name, I'll change it, I wasn't the one to decide on it though

#

I can't put it in OnValidate before that suggestion appears

vestal arch
#

the values do get created every time, though it's basically just 2 floats each

wintry crescent
#

but damn, I could've sworn vector2 and vector3 were classes! Why does float2 and float3 exist then?

vestal arch
#

that fits into a word on a 64-bit processor, so maybe that's optimized as a single instruction each, but i don't really know how structs work internally so im not confident

wintry crescent
#

in the Unity.Math library

vestal arch
#

probably implemented differently for ease of use vs performance?

wintry crescent
#

unity.mathematics*

#

perhaps

#

why did I have it in my head that vector3 is a class, though... huh

vestal arch
#

Unity Mathematics is a C# math library that provides vector types and math functions that have a shader-like syntax, similar to SIMD or HLSL. The Burst compiler uses Unity Mathematics to compile C#/IL code into highly efficient native code.

somber tapir
wintry crescent
night harness
patent perch
#

Hi
I want to deactivate my player input at a moment (I have several and want to deactivate it at the same time)
I tried Deactivate PlayerInput, doesn't work
I tried actions.Disable(), doesn't work
I have this config on my player prefab (default input system actions)

steady bobcat
#

If a new struct was passed as an arg Id expect it to be stack allocated too

#

I know mono is kinda shit but its probably not that shit

astral sky
patent perch
astral sky
#

Doesn't PlayerInput hold a reference to the user it creates?

wicked mountain
wintry crescent
timid shard
#

Idk if this is the right spot to ask but:
Can someone pls help me. I feel like I'm going crazy

I am trying to mod Schedule 1, and load in an asset bundle. I cannot for the life of me get it to load in.

I am using UnityEngine.dll, UnityEngine.AssetBundles.dll, UnityEngine.CoreModules.dll from unity hub folder version matching the one Scheule 1 was built on. I would appreciate any help

somber nacelle
#

modding discussions are not permitted in this server

#

you can typically find help in the game's modding community if you need help with mod related stuff

timid shard
zealous lava
#

Anyone is an expert on A* pathfinding 2D?

vestal arch
#

!ask

tawny elkBOT
robust dome
hexed pecan
#

Is that the aron granberg's package or what?

#

Because "A* pathfinding" doesn't sound very specific

#

It's a very common algorithm used in pathfinding

finite falcon
#

Hiya! I could really use some help with my raycasting code, I'm trying to make a laser-reflections game that involves the player shooting out light in the direction of the mouse, and reflecting it off of mirrors.

For some reason, the reflections work great on one side of the mirror, but not on the other. Does anyone know why this might be happening?

hexed pecan
zealous lava
#

I am using a* to detect the layer 'ground'. I want part of this 'ground' detected not to be walkable by the enemy, for example a wall or something like this. I added tag to A* as 'Wall' and then on the seeker y set the tag 'Wall' as not travesable. Then I set to the wall the layer 'Ground', a Box Collider 2D and the script GraphUpdateScene, with the only the Update Erosion not checked and the Walkability Value not checked. Modify Tag is checked and Tag Value is as Wall. But it does't work

#

Is like it doesn't change the wall tag

hexed pecan
finite falcon
rain minnow
tawny elkBOT
rain minnow
#

Everyone will have a better chance to look at it . . .

hexed pecan
#

That, but yeah this doesn't make sense:cs Vector2.Reflect(mirrorHitPoint, mirrorHitNormal)

#

Reflect is meant to be used with two direction vectors but you are giving it a position and a direction

#

Should probably replace mirrorHitPoint here with the direction of the first raycast

finite falcon
#

Ohhh that makes WAY more sense now, I changed it from
Vector2.Reflect(mirrorHitPoint, mirrorHitNormal)
to
Vector2.Reflect(playerMovement.aimDirection, mirrorHitNormal)
And now it's working great! Thanks for the help :]

fading swallow
#

I have an enemy with multiple colliders, one for detecting the player at a distance to chase, another to detect weapons that are attack, which I was leaving to the collider inside the CharacterController. My issue is how do I discriminate between which collider has been triggered? in

OnTriggerEnter(Collider other) other refers to the weapon that has triggered am I correct?

because right now any collider on my enemy with the isTrigger == true, inducing the chase collider is giving false positives for damage. So how would I mask out any other colliders on the enemy.

rigid island