#archived-code-general

1 messages · Page 350 of 1

dusky lake
#

I mean there are signs for the spoken words, maybe they use the arabic numerals when not explicitly writing it like "1" vs "one"

#

Create a static "Tags" class or an enum and put all your Tags in there, if you end up changing one you just change the string in that one and not 15 places in the Code

lone zealot
dusky lake
chilly surge
dusky lake
wide terrace
#

Just don't use tags 😁

chilly surge
#

Yes, the conventional wisdom is that instead of trying to use all the tricks to make a fundamentally flawed feature less flawed, it might be better off to just use something different.

lone zealot
#

Int to string should be a very trivial task for a localization system, I don't know why Unity's makes it hard (or maybe i just haven't found the easy way yet)

#

for new readers, i mean a 3 to "3" or "۳" depending on the locale. A 1500.5 to "1,500.5" or "۱،۵۰۰/۵"

dusky lake
#

Oh you even want decimal conversion and stuff, well I guess someone will have had that problem in the past and you should crawl github for C# solutions. This one sounds like such a general problem that there has to be a solution

#

Gets the RegionInfo that represents the country/region used by the current thread.

brave mica
#

I'm trying to implement a "shelf" system where items will be instantiated onto set positions. I'm having trouble figuring out how to account for different rotations. Any ideas on how I could make this work on more than just one axis?

wide terrace
#

or maybe rather their container object? 🤔

brave mica
#

When I do that this is the result. I'm no good at the math aspects but it seems like the problem is in the position rather than the rotation. Like I want to find the position using the rotation of the container but not sure how

wide terrace
brave mica
# wide terrace Ah sure... What's the code look like?

boundsX/Z --- The minimum bounds of the BoxCollider of the container
capacityX/Z --- The total number of items that can fit in the shelf X/Z axis (This is calculated in another method but is working as intended)
paddingX/Z --- The padding between each item
itemSizeX/Z --- The unit size of the item on the shelf

float posX = boundsX + (itemCount / capacityZ * itemSizeX)+(itemCount / capacityZ * paddingX) + (itemSizeX/2) + paddingX;
float posZ = boundsZ + (itemCount % capacityZ * itemSizeZ)+(itemCount % capacityZ * paddingZ) + (itemSizeZ/2) + paddingZ;
Vector3 pos = new Vector3(posX, containerHeights, posZ);
GameObject go = Instantiate(items.gameObject, pos, transform.rotation, transform);

It's sloppy so lmk if there are any confusing bits 😅

mild quail
#

is there a way to have 2 event systems with completely separate gameobjects that are interactable? I have 2 event systems in my game that I'm toggling between but it's possible to select the old things still when the new event system is active since the new event system is letting the user interact with the other gameobjects

wide terrace
#

Ah wait... bounds is already local. I am very rusty 👀

wide terrace
brave mica
wide terrace
delicate zinc
#

I am incredibly confused by an issue i'm having on this script.

https://hastebin.com/share/lezaculiko.csharp

I got this script, on Awake i'm getting characterBody and storing it in a Property, however, if i use the ToggleCombat context menu, it throws a null reference exception on line 20.

What could cause the property to null itself for apparently no reason? using cross referencing shows that the only two things interacting with the proeprty is the setting of the value and the method call

#

Awake is getting called according to me breakpoint debugging, but if i put a breakpoint on the property itself nothing happens (the breakpoint isnt getting hit)

weak spruce
#
using System.Collections;
using UnityEngine;
using UnityEngine.UIElements;

public class SheepController : MonoBehaviour
{
    public Transform Dog;
    private float speed = 3f;
    private float distance = 2.5f;
    private Animator animator;
    public LayerMask hitlayer;

    void Update()
    {
        Vector3 origin = transform.position;
        Vector3 Direction = Dog.transform.position - origin;
        Dog = GameObject.FindGameObjectWithTag("Dog").GetComponent<Transform>();
        animator = GetComponent<Animator>();

        RaycastHit hit;

        if (Physics.Raycast(origin, Direction, out hit, distance, hitlayer))
        {
            animator.Play("Run");
            Quaternion targetRotation = Quaternion.LookRotation(-Direction);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 100);
            transform.Translate(-Direction * speed * Time.deltaTime, Space.World);
        }
    }
}
leaden ice
#

Can you show the full stack trace of your error?

leaden ice
weak spruce
leaden ice
#

btw .GetComponent<Transform>(); is never necessary, you can just do .transform

delicate zinc
leaden ice
delicate zinc
#

ok, i think i was indeed calling it on a prefab accidentally clueless .

#

oops

mossy oyster
#

Hi, I've got a question, I have a game with levels and I have an editor inside the unity editor to make them but I don't know where to save them (I don't want/can't save them in different scenes etc...). I want to save them in a json (it's actually just some lists of points), problem is idk how to create a json file inside of the assets folder neither how to access it (the path), how do I do that? Or is there a better way than json to save lists of vector2D/bools/int

brave mica
wide terrace
#

or collider.bounds.min?

knotty sun
# brave mica the latter

I know this might be a bit simplistic thinking but if you are having problems placing objects onto the rotated shelf why not unrotate it, place the objects then rotate it back

wide terrace
# brave mica the latter

Okay, so I think they are in world space. If you can switch to the former I believe it should just work. Otherwise you'll need to add them to the position after it's transform.TransformPoint()'d rather than before

brave mica
proven scroll
#

So im trying to make a puzzle game where you collect words in the world and once you collect them they go to the "TV' (the place where they will put the puzzle together, which is all in the same scene) once they are in the tv they cans be collected anymore and you are able to drag them around and put the words in specific points on the TV if it is the correct point it will stay if not it will return to the original place inside the TV

What would be the best way to go about this as there will be many different words

rigid island
proven scroll
#

Okay So i made a scriptable object that i can reuse to have diferent words, and for testing i have 2 different words in my scene and when i collide with one they both get triggerd even though i didnt touch the other one

and was wondering how the best way to go about this structure wise im just getting so confused and turned around on how to get this going :/

vivid wind
#

Are nuget packages available through the unity package manager? I'm considering converting my external utility library to a package, but I have some dependencies such as DependencyInjection and abstractions, and a few others. The information I've found on the topic is mixed at best. AI seems to thinks it possible, but found a 2020 post that says nuget packages arn't supported.

lone zealot
pliant spade
#

Hi, Anyone knows how to set the {Level} variable of a smart string from a script?

hidden flicker
#

Is there a way to get the normal of a face just from OverlapSphere?

lone zealot
pliant spade
spring creek
keen lantern
#

Hey, I am receiving this weird problem when Im trying to instantiate an object. It does instantiate in the scene, but the object tends to be disabled in the scene when it instantiates. Any reason to why this might be?
Heres the instantiation line of code if needed: equippedItem = Instantiate(selectedItem.heldItem, playerHand);

#

the heldItem is a GameObject btw

pliant spade
# lone zealot Yes

Well it does not exist, neither from LocalizedString or LocalizeStringEvent

rigid island
lone zealot
keen lantern
#

So I simply dont really understand how its instantiating as inactive

#

Oh apparently something about the network object is causing the problem

#

I shouldve know that stupid multiplayer is the issue here

pliant spade
lone zealot
#

Because it's mutable

pliant spade
lone zealot
pliant spade
#

Yea I get it.

#

Thank you!

fiery blaze
#

anybody maybe know why this isnt working?

wide terrace
fiery blaze
wide terrace
#

Is ab a Rigidbody2D?

fiery blaze
#

no 3d

wide terrace
#

Check out the docs - the error is accurate, there's no way to call it with three arguments

fiery blaze
#

oh wait

#

im dumb

#

i meant to use rigidbody smh

spring creek
#

You should pass in the Vector it is expecting

fiery blaze
#

it seemed to be fine

#

command worked

spring creek
fiery blaze
#

yeah i just seemed to figured it out Loll

coral phoenix
#

Hi, I'm having some problems with the DontDestroyOnLoad objects, i'm trying to get the component "Unit" that is in: party -> Teammate1 -> Unit, but when I assign it, it doesn't refer to the actual object, I think it is creating a new "unit" component to reference

#

i think the problem is in line 20-24, but I can't find a way to fix it

vale wharf
#

Trying to get a bone (selected) to face towards player. However, due to the fact the bone has a weird axis layout (Y is forwards), I am having difficulty trying to get the code to work.

var playerDerivative = (PlayerController.instance.transform.position - headTransform.Value.position).normalized;
var rot = Quaternion.LookRotation(playerDerivative, Vector3.forward); //Since Z is up for the bone.


headTransform.Value.rotation = rot;

Am I doing anything wrong?

fervent coyote
#

Hey there, I'm wanting to implement a way for the player to add custom scripts to weapons, so when they attach the script to the ScriptableObject's variable, instead of running on built-in code it'll instead run the custom code, however, The code WILL have to be static (Although I could always just make the script attach to the player and then remove itself when switching weapons), and I know that you can't use the monobehaviour itself in the code, as you have to future proof for pretty much every class name. Anyway I can do this?

cold parrot
fervent coyote
#

If they so wish, yes, specifically for weapons.
You know how the Source engine has specific scripts for weapons? Such as physcannon (Gravity Gun), something like that, although I'm hoping for a way to be able to reference the script as a variable, and either it'll add the component to the player/npc when it is equipped, or will call static functions

It would work like:
(In the ScriptableObject)
public Script Weapon_CustomScript = null; (I know that Script is nonsense, just psuedocode)
(Custom Script)

{
    public static void Weapon_PrimaryFire(GameObject origin)
    {
        Handler_Gamehandler.Game_GetGamehandler().Astro_WriteToConsole(origin.name + " Primary Fire");
    }
    public static void Weapon_SecondaryFire(GameObject origin)
    {
        Handler_Gamehandler.Game_GetGamehandler().Astro_WriteToConsole(origin.name + " Secondary Fire");
    }
}```
When the player runs the primary or secondary fire, it would call the function, regardless of class name
cold parrot
#

Anyway, if that’s what you want you should embed an interpreted scripting language with a limited and well curated API for game functionality it can use.

#

Stuff like that is often done with Lua.

fervent coyote
#

Ah, I see
Is there a way to have a variable be set to a script? I can't seem to find it, and I'm not sure if it's a niche thing or not

cold parrot
#

Very niche

#

Technically you can allow a player to call any method on any GameObjects that is loaded in the game via SendMessage()

fervent coyote
#

Oh, I'm well aware, although some people have said that is a very bad idea

#

I'm more or less concerned how I can get a script to be a variable, so I can put the script unto the player/npc

prime moat
#

Guys i have a quick wuestion, im making a tank game and im going to start working on the tech tree now, basically like the one in warthunder in which you can unlock tanks etc. I was wondering if this should be done with normal script or is it better if i do it with ScriptableObject

cold parrot
lean sail
cold parrot
#

technically you could compile a script from source at runtime, load that and run it, but idk how unity responds to that kind of thing. In any case its not a good idea.

fervent coyote
#

Well, that wouldn't fit what I would be looking for, unfortunately...
I was hoping that it would be as easy as assigning a variable to the variable, and that static functions would be called

cosmic rain
fervent coyote
cold parrot
fervent coyote
#

I found MonoScript, but there doesn't seem to be a way to actually call functions from it

cold parrot
#

you have to build that hook for function calls yourself. You can use C#'s reflection features to access/call pretty much anything

cosmic rain
#

Ah, it's a bone... A proxy wouldn't work then.

fervent coyote
#

Ah, I see

cosmic rain
wide terrace
#

Also players exchanging C# scripts with access to native libraries is terrifying 😬

fervent coyote
#

I think I may be a little dum in the head, sorry 😓
I also didn't think of the ramifications of that, either

I just want players to easily mod my game, if they so desire too

#

But I'm not really sure to implement LUA or other DSL languages

cold parrot
cosmic rain
#

Honestly, this kind of feature is something stretching to the advanced level. And even if you have long years of experience with unity and coding, it would require a thorough research. Not something you can just get an answer lightly on discord.

fervent coyote
#

I was hoping it would, but thank you for your help regardless

#

I'm also... intermediate, to be honest

#

Although, I DO have addons working (Loading scenes/maps, ScriptableObjects, etc), just custom scripts would be awesome you know?

cold parrot
#

its awesome but also extremely powerful, hence the complications

cosmic rain
#

It's not impossible, you just need to do proper research.

cold parrot
#

if unity were written in python or javascript this kind of thing would be trivial, but you'd also have only 1% of the performance

rustic rain
#

can you serialise with a different number than the actual property?

cold parrot
rustic rain
#

F transform looks ugly

cold parrot
#

depening on your serializer your can

rustic rain
#

i want to just be transform

#

im using odin

cold parrot
#

you can put a custom label on anything with odin

#

doesn't change the serialization though

cold parrot
lean sail
#

People will probably mod it faster than you can make logic for them to mod it with

fervent coyote
#

Yeah, alright, thank you!
As an example, each weapon is a ScriptableObject called ScriptObject_Weapon

cold parrot
# fervent coyote Yeah, alright, thank you! As an example, each weapon is a ``ScriptableObject`` c...

also worth considering that unity is in no way designed to be a framework for making another game-engine or any kind of application that deals with data ingress. You can build all that yourself, but you get no help from unity. Those who tried (that i'm aware of) have abandoned the approach in their v2 if they have survived. Mod "support" extends only to assets, configuration and interpreted scripts (if you provide the runtime for them).

vale wharf
#

afaik I am exporting this model correctly.

cosmic rain
cosmic rain
lean sail
frosty coral
#

for some reason my audio source called "Pop" isnt playing but every other sound is playing. its supposed to play when i build something or drop a human into the scene

rigid island
#

or some event driven too

fervent coyote
#

Hey, so, how can I rename a class without losing the variables located within?
For example, I hate that my current class is called Entity_Transition, and want to change the #C script and class to Entity_EventChangeMap

However, I am worried (Because I have done this before) that when I do, I'll lose a lot of progress cause I use this a lot, can anyone help me out here?

rigid island
#

you wont lose the vars but might reset the values. I dont remember lol

fervent coyote
#

Oh, I meant the values on a gameobject

dusk apex
#

Git backup your project. Take a picture of your settings before modification or write a script to save/load your scene settings.

lean sail
#

i dont think ive ever lost values when i renamed a script. Thats even when I rename it entirely in visual studio, while apparently you're supposed to rename it first in unity

#

but yea not like anything can go wrong if you use version control

fervent coyote
#

I use Github GIT

rigid island
#

github just hosts GIT repositories

#

but there are others, bitbucket, gitlab etc..

wide terrace
#

If I wanted to store instances of distinct classes which share a common interface, key them by type, and expose an API similar to GetComponent<T>(), would this be a remotely reasonable means to accomplish it?

private Dictionary<System.Type, SystemController> _systems = new();

public void AddSystem<T>(T system) where T : SystemController {
    _systems.Add(typeof(T), system);
}

public T GetSystem<T>() where T : SystemController {
    if (_systems.TryGetValue(typeof(T), out SystemController system))
        return (T)system;

    return null;
}
#

I guess they don't necessarily need to be keyed by type - I just found myself reaching for something akin to a JavaScript Symbol

chilly surge
#

What does JS symbol do in this use case? JS symbol is essentially just a pointer that can be used as property key, I don't see how that's related.

wide terrace
#

I just mildly fear I stumbled into some poor pattern or implementation. This is me mostly just flailing around a bit

chilly surge
#

Yeah I just don't see how that's related to JS symbols, but otherwise that code seems fine.

wide terrace
#

Thank you I appreciate it!

chilly surge
#

JS symbol really just is a reference type, so if you want something like one, it's just new object().

wide terrace
chilly surge
#

JS symbol is the same too, you could just do const myKey = {} and that guarantees uniqueness. The only reason JS symbol has to be invented is because you can't use that as a key (so you can't do dict[myKey] = 42)

broken light
#

is unity's mesh RecalculateNormals() method on github? need to see how they calculate it since mine isn't correct

wide terrace
spare island
#

I have a bit more of an abstract problem, but I'm trying to figure out how I should structure my combat in my code.

So I have an actor who has the ability to attack with either their fist or with a weapon, and there are different types of weapons with different animations, combos, etc. What is responsible for doing the damage? The sword object itself, a combat script, the receiving party.. etc

it's very confusing

#

I'm looking not for a direct answer for this exact question but maybe some pattern/design solution commonly used for this problem

edgy stump
#

Hey guys

#

Why my Backflip not working?

#

Well, it's working

#

but only rarely

#

This is a prototype, ignore the crooked code

edgy stump
nocturne wyvern
#

Hello
I have this structure

 [Serializable]
    public struct RelationshipConfigData
    {
        public RelationshipStatusConfigData[] Statuses;
        public int pointsPerMessage;
        public int pointsPerMessageLike;
        
#if UNITY_EDITOR
        [Button]
        public void CopyAsJson() => CopyJsonUtility.CopyInBuffer(this);

        [Button]
        public void PasteJson() => CopyJsonUtility.FromBuffer(ref this);
#endif

and there is such json

{
  "Statuses": [
    {
      "id": "status_strangers",
      "name": "Strangers",
      "initialOpened": true,
      "MaxPoints": 75,
      "transactionID": "status_default"
    },
    {
      "id": "status_friends",
      "name": "Friends",
      "initialOpened": false,
      "MaxPoints": 75,
      "transactionID": "status_friends"
    }
  ],
  "pointsPerMessage": 1,
  "pointsPerMessageLike": 2
} 

I'm trying to convert this json into an object via

var result = JsonConvert.DeserializeObject<T>(jsonData);

but an error occurs on the device

 ExecutionEngineException: Attempting to call method 'System.Collections.Generic.List1[[RelationshipStatusConfigData, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]::.cctor' for which no ahead of time (AOT) code was generated.

some other configs converted normally and there were no problems, what’s wrong?

knotty sun
#

show !code for RelationshipStatusConfigData

tawny elkBOT
nocturne wyvern
# knotty sun show !code for RelationshipStatusConfigData
 [Serializable]
    public struct RelationshipStatusConfigData
    {
        public string id;
        public string name;
        public bool initialOpened;
        public int MaxPoints;
        [TransactionID(TransactionTypeConst.Status)]
        public string transactionID;
    }

could this be due to the fact that there is an array of RelationshipStatusConfigData and not a list?

knotty sun
nocturne wyvern
knotty sun
#

I am presuming this is Newtonsoft Json

nocturne wyvern
knotty sun
#

I know why it is throwing the error but I have no idea how it gets that far. The easy fix would be to change the array to a list but that should not be necessary

nocturne wyvern
#

I found this solution, but I still don’t understand what this is connected with, I’ll try it

It might be worth updating the version of Unity or the version of newtonsoft itself

knotty sun
#

yeah it is the=managed code stripping.
simply adding a List<RelationshipStatusConfigData> somewhere will solve it.
I'm guessing JsonConvert first builds a list then converts the List to an array which would make sense because it cannot know the size of the array whilst it is parsing the data file

nocturne wyvern
knotty sun
nocturne wyvern
knotty sun
#

you don't that is the whole point

nocturne wyvern
#

in one of the projects I also used such a thing

knotty sun
#

just by having the code with preserve will ensure the the List<RelationshipStatusConfigData> constructor will exist at runtime

knotty sun
nocturne wyvern
#

i will try to use this

knotty sun
#

you still need the [Preserve] attribute

nocturne wyvern
#

this is all?

knotty sun
#

yep

warm badger
#

can i set custom frustum culling range in Graphics.Drawmesh function?? I want to render a lot of grass inside a custom range...but not inside the whole frustum range of the camera..what should i do?

maiden fractal
warm badger
maiden fractal
# warm badger i couldn't get it... can you explain a bit?

Each time you call Graphics.DrawMesh, it's basically a draw call which are quite slow if you call it thousands of times. Instead you should pack your data to ComputeBuffers/Textures and render all the grass at once with Graphics.DrawMeshInstancedIndirect or similar method. It's bit harder to set up but it's definitely worth the time to drastically improve the performance. The problem with the instanced methods is that they don't do any frustum culling at all which takes us back to the original question. Since there's no frustum culling happening by unity, you must implement the frustum culling yourself and therefore you can do your own range stuff there.

warm badger
maiden fractal
warm badger
#

yeah! i want to render a lot of grass meshes

maiden fractal
#

Then Graphics.DrawMesh won't work as I said. There's also a lot of raedy to use grass systems available if you don't have the time and effort to put in one

warm badger
#

yeah...looks like a long way to go...

vale bridge
#

I read online that says that unity uses the Mono C# compiler, produces Bytecode(IL + metadata) then uses the Mono Runtime to translate that into the platform specific Machine Code

vale bridge
#

And the reason why unity is able to export cross platform is because of Mono's role in the above sentence?

knotty sun
#

indeed

vale bridge
#

I'm also confused on if the compiler for the C# scripts matter in terms of cross platform ability

#

if we have two different compilers and then feed the bytecode into mono runtime will they both be able to be translated into platform specific machine code?

vale bridge
knotty sun
#

yes it does because Mono .Net IL is not the same as MS .Net IL so if you compiled using MS .Net (at least for the versions Unity uses) it may cause problems cross platform

vale bridge
#

I see

#

Is it because Mono .Net libraries(I'm under the impression that .Net is a giant conglomerate of libraries) might be diifferent to MS.Net libraries?

knotty sun
#

exactly

vale bridge
#

So then is the reason mono developed because MS.net didn't have cross platform in mind so they decided to translate that functionality so to speak themselves?

#

Do the two follow some sort of agreed upon guideline so the .net base functionalities are somewhat similar, or do they now do their own things but develop under the same ".net" name

knotty sun
#

that is basically correct, then MS reabsorbed Mono and renamed it Xamarin To bring some kind of normalization but there are still many differences. When (if) Unity eventually migrate to .Net 7 + then all of this should go away

vale bridge
#

TIL Xamarin and Mono are the same thing

vale bridge
#

Oh nvm it stands for intermediate language to Cpp

#

Does that mean instead of mono runtime it uses IL2CPP instead, but still uses mono libraries during compilation?

knotty sun
vale bridge
knotty sun
#

exactly

vale bridge
#

So if I'm gettin gthis correctly, IL2CPP only works on platforms that CPP is able to compile into native binary

#

or rather platforms that use native binary

cosmic rain
knotty sun
#

which will be all platforms, the important thing is that code compiled for one platform will not run on a different one

cosmic rain
#

Everything runs on C++ or C

vale bridge
cosmic rain
#

To be precise, C/C++ compiles to almost any platform native code

knotty sun
#

yes, to be more precise, platform specific native code, which is why it cannot be cross-platform

vale bridge
#

I did a little reading just now and my interpretation of the mono vs il2cpp is as follows:

  1. Mono is cross platform because it translates into machine code on the fly from ByteCode(JIT)
  2. IL2CPP is ahead of itme compileation which because native machine code is different, is not cross platform, but since CPP can target any native machine code you can export to any platform

Which makes me wonder if cross-platform means strictly that you can run the smae piece of code on different platforms

cosmic rain
#

To be fair, "not cross-platform" doesn't really matter here. It's not like you can run a mono build for a specific platform on any other platform.

vale bridge
#

That's what I was wondering as well

knotty sun
#

This 'you can export to any platform' is the wrong concept. you do not 'export' you 'build to'

vale bridge
#

As in building to a specific platform's native code?

knotty sun
#

yes

cosmic rain
#

Mono and dotnet are cross-platform as frameworks. Meaning that their API is able to be compiled to any supported platform and is usually guaranteed to work the same way. On the other hand, if you're building a C++ app, there would be a lot of platform specific code, platform specific libraries, etc...

vale bridge
cosmic rain
#

Unity takes care of that for you regardless of whether you build a mono or il2cpp, although there are some limitations

vale bridge
vale bridge
knotty sun
#

If you look at the workflows it's quite simple
Source->.Net Compiler->IL->.Net Runtime->OS->bare metal
or
Source->C++ compiler->native binary->OS->bare metal

cosmic rain
knotty sun
vale bridge
vale bridge
cosmic rain
warm badger
#

is it possible to make Graphics.DrawMeshIntanced objects support lightprobes by any means?

knotty sun
#

not happy with the word translate because a compiler does a great deal more than that

cosmic rain
vale bridge
#

Any uhh recommended sources for this type of stuffUnityChanwow

cosmic rain
#

If you're interested. I wouldn't say it's absolutely necessary for a gamedev.

#

If anything, I'd rather stay a way from low level stuff and let smarter people deal with it

knotty sun
vale bridge
#

At least now I somewhat know how unity cross platform works

#

Thank you both for this incredibly long dicussion, I definitely understand this much more than I did before

#

Really appreciate it

knotty sun
#

thats not just Unity cross platform, the same basic structures are true for most modern languages like Java, JavaScript and Python

#

in fact C and C++ are somewhat on an anachronism as they compile to native code, not many modern languages do

knotty sun
#

only in terms of performance, C and C++ will always out perform anything else

vale bridge
#

Gotcha

knotty sun
#

the closer you are to the metal, the faster the code will run, this is why we still write device drivers in assembly code

vale bridge
#

Thank you for the explanations

rough sorrel
#

Hi. One question, is it normal that using Invoke(nameof(DoSomething),0); is faster than doing DoSomething();? Like, what are the downsides of using Invoke then?

knotty sun
#

Invoke can never be faster than a direct method call

rough sorrel
#

then idk what I'm doing wrong with my setup but it is telling me that it is faster. Let me see if I can do it again and show it

cosmic rain
#

And what's telling you that it's faster?

rough sorrel
# cosmic rain What kind of "setup" do you have?

The setup:

public class CodeTesting : MonoBehaviour
{
    public int iterations = 10000;
    
    [Button]
    public void Iterate()
    {
        for (int i = 0; i < iterations; i++)
        {
            Invoke(nameof(DoSomething),0);
            //DoSomething();
        }
        
    }

    public void DoSomething()
    {
        Debug.Log("smth");
    }
}
rough sorrel
quartz folio
#

That is never going to work as a test case to profile

#

the likely reason that there's a difference is because the stack has been thrown away when you use Invoke, so the overhead of extracting the stack for the log is lower

#

it's got absolutely nothing to do with how you're calling the method

rough sorrel
#

ohhhhh okay

#

I didn't know that. Then ignore what I said before. Thanks

hushed cloud
#

Why does my layer mask make this check box ignore all layers and not just layer 10? 😕

bool isColliding = Physics.CheckBox(boxCenterWS, wheelContactArea * 0.5f, wheelParent.rotation, 10);
knotty sun
dusk apex
hushed cloud
#

I did try GetMask and NameToLayer without much success earlier

1 << 10
This did the trick though

dusk apex
quartz folio
midnight coral
#

Hey does anyone know how to stop 2dynamic rb2d from pushin each other

dusk apex
midnight coral
#

so when walking into each other they both stop the other

#

while not being pushed backwards

dusk apex
#

Sounds like you'll have to implement some custom edge cases for non static colliders not wanting to treat each other as dynamic objects - modifying drag could probably yield the behavior you'd want but might create other unwanted issues.

midnight coral
#

for example?

spare island
#

So if touching other dynamic body:
Velocity = 0, current, 0

midnight coral
# spare island So if touching other dynamic body: Velocity = 0, current, 0

This can work but after touching a body they stay inside each other meaning that the velocity gets set to 0 only once at the beginning of the collision afterwards the player can continue to try to move inside the enemies collider which will in turn push the enemy, i dont know if this is what will actually happen though

spare island
midnight coral
# spare island what about negative velocity where it pushes them away from eachother?

what i mean is that lets say theres an enemy staying still the player can run into the enemy the enemies velocity will be the sames as the players( same direction) the player will stop moving after hitting the enemy the enemy wont get pushed since we set the velocity to 0 at the start of the collision afterwards the player can decide to move again and this will push the enemy, if i make it so if the enemy checks constantly if a collision is happening so i can set the velocity 0 this will make the enemy not get pushed even after the player moves again after the initial collision but the enemy wont be able to move itself out unless the player moves out of the collision as the velocity is being set to 0 constantly

spare island
#

would it work to just make them heavier?

midnight coral
#

ive tried it

#

it doesnt help

spare island
#

Increasing drag?

midnight coral
#

the player might not push the enemy but the enemy can push the player and the enemy can push another enemy

midnight coral
#

ive tried bounciness and friction to 0 as well

#

on the colliders

lean sail
#

Well all of those things are completely unrelated, so its not like itd do anything

#

Unless you set the velocity every fixedupdate to what you want for both objects, you cant really do what you want using unitys rigidbody.

spare island
#

its not an ideal solution ik

midnight coral
spare island
#

oh idk if it supports 2D

midnight coral
#

yeah this is why im stuck

#

the only thing that has kinda worked

#

is having enemies and the player have a child object with rigidbody2d set as kinematic with continues collision detection

spare island
#

do you actually need a dynamic rigidbody on the player

midnight coral
#

and having the collider of that child object bigger than the enemies or players collider

midnight coral
#

but yea i do

spare island
#

why exactly?

lean sail
#

You simply cannot have an active rb to achieve what you want. If you use it, it will be pushed around by other things with velocity, end of story

midnight coral
# spare island why exactly?

trying to make a 2d souls like and pushing the enemies or having no collision between enemies just feels wrong to me

#

i want it to be just like the games where the player can run into an enemy and nothing happens

#

or vice versa

spare island
#

how about using a charactercontroller?

midnight coral
#

doesnt work for 2d

spare island
#

is it?

midnight coral
#

yea if you have a 2d collider

#

it will say when trying to add it

lean sail
#

there are many tutorials out there for simple 2d movement

midnight coral
#

yea but all that ive seen are just no collision between enemies

#

or custom collision detection using a kinematic rb

#

thats what im thinking

#

of doing rn

lean sail
#

those tutorials would go through custom collision detection. of course theres no collision detection if you arent using unitys physics, which you cant in this case

#

But really you can just cast to check if anythings in the way, and not move into the object. If platforms/other stuff can move into your character, then you'd need to depentrate somehow

midnight coral
#

the not move into the object would work

#

but lets say i have a enemy that will lunge at the player

#

i need the enemy to have collision so that when it hits the player it stops

#

but is able to not be pushed

#

etc

lean sail
midnight coral
#

yea maybe

#

but thats the aproach im leaning towards the most

#

i just was trying to see if there is another way

#

thats simpler

lean sail
#

and it'll still do its own depenetration

steady moat
#

Use Raycast/Boxcast to limit the movement.

midnight coral
#

i need them to collider with other enemies and the player and not get pushed around or push others

#

would i need to raycast as well for them

steady moat
#

The same, if you do not want them to move when they are colliding.

steady moat
midnight coral
#

i was trying to see if theres a few options i can set and be done with it

#

xD

steady moat
#

Then buy an asset that does it.

midnight coral
#

I dont know if there is any

lean sail
#

honestly making your own 2d character controller should be fairly easy

#

3d is a different story

steady moat
#

You can always try to use multiple layer but I am not sure how it would behave

midnight coral
lean sail
#

this is the same suggestion ive been saying most of the time, and same as what simferoce is saying

spare island
#

im 90% sure there are are already 2D character controllers available on github too

#

i'd be shocked if there was nothing available like what you want

steady moat
#

Usually, I like to only push enemies outward instead of preventing the collision

#

In other words, players/enemies/enemies does not interact

south cairn
#

I need advice, I'm making a card game and have cards stored as ScriptableObjects (CardSO) which have various effects also stored as ScriptableObjects (CardEffect).
And I want to have those effects to have their own little variables that can be affected on runtime by either their own effect or another card's, now currently I'm creating a separate MonoBehaviour script for every different effect (e.g.: the AddRequiredComponents in DamageTargets)
which can of course easily pile up a ton of different MonoBehaviours just for one card, and therein lies the problem.
How do I restructure this so that I don't have to instantiate a new MB for every effect without using ScriptableObject.CreateInstance() ?

cold parrot
# south cairn I need advice, I'm making a card game and have cards stored as ScriptableObjects...

experience of other people in this server with making a card-game (with arbitrary rules, not just poker) boil down to: it is very difficult to make the rules for these cards in a statically typed, compiled language and regardless of how you reach your goal, you will have created what basically amounts to a ill-conceived and badly maintained domain specific language. Their advice is it embrace that fact and just use an interpreted, lisp-/lua-like language from the start to represent your card-rules. for reference (never used these libraries) -> https://sharpscript.net/lisp/unity -> https://www.moonsharp.org/

#

reason being that declarative rules generally do not work out in the end and you will eventually want to add procedural code to them to keep things simple.

south cairn
hexed oak
#

I think the advice "just use a different language" is an odd approach given this is a unity discord lol

#

But he presents a good point to the advantages of functional languages

#

Kinda reminds me of Greenspun's tenth rule

south cairn
cold parrot
# hexed oak I think the advice "just use a different language" is an odd approach given this...

the advice is not to use a different language its an advice about architecture and recognizing what the actual problem is one wants to solve. Its also not about "functional" languages but about a language where code is also data and can be manipulated while executing. Lisp in particular is excellent for situations where you have to dynamically invent a custom world in which to operate in while being extremely simple from a syntax/operator perspective.

tardy hull
#

Hey, does jobs and burst compiler work in browser games?

dense rock
#

Is there a way to make the screen darker besides a specific rectangle? I guess it should be something with UI mask maybe? I'm thinking about some inverted mask
or cut out a part of an UI image

cold parrot
tardy hull
steady moat
# south cairn I need advice, I'm making a card game and have cards stored as ScriptableObjects...

You can use SerializedReference instead of MonoBehaviour. Also, I usually use the Factory Pattern for such situation.


public class DamageCardEffect : CardEffect
{
  public class Effect : CardEffect.Effect
  {
    //Actual runtime behaviour
  }

  public CardEffect Build() { ... }
}

public class CardDefinition 
{
  [SerializeReference]
  public List<CardEffect> effects;

  public Card Build()
  {
     foreach(CardEffect effect in effects)
       effect.Build();

     //Add other effect from other sources
     return card;
  }
}

olive fractal
# south cairn yes I do have a list of CardEffect in the CardSO , so a list of ScriptableObject...

Sorry if I misread your needs, but have you heard of the idea of Data Transfer Objects (DTO).
It is when you have a class that you acts as an intermediate layer as a go between for objects needing to read, write, move, or edit data.

In Unity some people use DTO with scriptable objects.
Example for an RPG that has crafting. The games items are scriptable objects and you want to have your players enchant weapons and save them, so you need to edit the item's properties of the scriptable object.

What some people do is they use a DTO that reads the initial values of the scriptable object and from there on in runtime edit the properties of the DTO.
So the DTO acts like the runtime data to edit, move, and do anything with.

steady moat
olive fractal
#

In normal applications DTO are just used to encapsulate dara and transfer it between different systems or layers in the application.

#

In Unity you can sort of use a fake DTO like a struct, record, or a normal class that inherits from nothing.
You can think of the Scriptable Object as the layer of the game app that contains data like a database and use a fake DTO class that reads the values of a scriptable object and have other runtime classes used that fake DTO for example.

It is useful for the chain broker pattern.

cold parrot
#

it might be better to think of an SO as the immutable config state of a "thing" and that fake-DTO as its separate mutable state, whether that is bundled into a struct or represented as primitives in multiple lists would not change its nature, but if you call it a (fake)DTO, you force the whole story into OOP think which might actually be counter-productive.

olive fractal
#

For his case I think what @cold parrot mention would be more relevant to my comment. Now that I read more of the previous conversation.

cold parrot
#

there sadly is just no way to do all this in a nice way.

#

in theory you can, it can be clean, you can make nice interfaces and algebraic types and higher order functions and all that, but its very impractical.

#

thats probably one of the reasons why so few card games get made that have non-pattern-based rules.

olive fractal
#

Honestly it might be a good idea to chart out the flow of how you want a pattern to work in game.
Than see what possibilities you need to work within a contained thought process for and go from there.

I found when working with systems that require a lot of extendibility, customization, and complex pieces doing something like this helps.
Do note this is a full on Metroidvania character controller for players, NPCs, and enemies so had to zoom in only on a piece of it because it is a chunky boy.

cold parrot
olive fractal
cold parrot
#

By now I firmly believe that without a ‘map’ you guarantee that the team goes nowhere and with a rigid map you guarantee that you will be building something useless.

olive fractal
#

Sad, but true words. When it comes to coding and making a map for things some people, including me I admit, might miss the mark sometimes.
Think at this point maps are meant as a way to help visualize the flow of intent for what you are coding and to be able to visualize different pieces that are connected to each other.
Including data being sent from one object to another or calling another objects function.

Maps might be a good thing to think of a guide on an always changing world. It helps get you near your destination and keep on track, but it should never be fully used as a concrete thing that can't be changed.
Through out development change is okay. The importance is learning how to set up code to allow for changes without breaking everything and having to refactor entire classes.
All hail interfaces and abstract implementations as long as they are not over used for that one.

cold parrot
#

the important thing is to realize where you are and where you can go from there. It’s so easy to dream about the ocean that you forget that right now you need most of all climbing gear.

olive fractal
#

What I read was mapping is a good objective tracker.
What my mind was thinking SCOPE CREEP SCOPE CREEP in your dreams.

rotund burrow
#

I want to make a jump pad. Normally i would write a script for a jumpPad object where OnTriggerEnter would push the player. However i'm not using a collider or rigidbody for the player (i do everything with raycasts). So how would i approach this issue? I was thinking attaching a trigger collider to player and calling OverlapBox on the jumpPad object.

lean sail
rotund burrow
lean sail
rotund burrow
#

i would have to do that for all units in the game in the future

lean sail
#

But honestly if your game lags from just kinematic rb and colliders alone, you're probably doing too much

frail dust
#

Hey everyone, I am an intermediate unity developer. Made two 2D Games for Android on my own. Also I have made one 3D game by following a tutorial.

I really want to understand how do I proceed further in my game dev journey? Specifically like shall I watch more tutorials , or learn more about C#, or just start making my own original projects (clones as well) without any help?

#

I just need a little guidance or a basic roadmap so I pave the way properly

leaden ice
#

Seek help as you run into problems

frail dust
#

Also Shall I just stop watching whole long hour tutorials? because I really think that tutorials have wasted my time. Not that those videos were bad, but How I utilised them were pretty dependent

lean sail
#

You definitely shouldnt be watching step by step tutorials that make a super specific feature. Most of the time you'll have trouble actually expanding on it. These are the tutorials where they type code on screen in real time.
Generally you should be looking up how to do a concept and try implementing it how you need it

frail dust
frail dust
lean sail
mossy oyster
#
while(GameObject.FindWithTag("LevelEnd") != null){
            Destroy(GameObject.FindWithTag("LevelEnd"));
        }

Any idea of why that would create an infinite loop?

lean sail
#

Look at the docs for destroy, it isnt destroyed instantly.

mossy oyster
lean sail
#

If you're a beginner, it likely belongs in the beginner channel

#

But please cache those objects in an array or something. This hurts to look at

mossy oyster
#

Changed to DestroyImmediate (it also fixed the problem that Destroy() is only effective at runtime and not from the editor)

wraith cobalt
clear oriole
#

Input.mousePosition;

Why is this so inaccurate for UI its like pretty far off from the mouse position

somber tapir
rigid island
#

most cases with UI you want to move the anchoredPosition of the rect transform

vagrant blade
#

If it's just generic settings, then it's fine. That's what player prefs is for.

rigid island
#

save to file or PlayerPrefs

lone bone
#

Unexpected behavior from GridLayout.WorldToCell()

#

Everytime I write a new thread, the act of typing it all out brings me to a solution....

You all are my rubber ducky.

lean sail
#

You are likely better off not using it. If you have to save anything custom you're gonna be writing it to file anyways. Might as well just save everything using the same method, and at least writing to file is easily visible for everyone.

spare island
#

(dont use playerprefs for anything besides maybe options)

plush ridge
#

i have a script that checks what type of ground the player is on and then plays the footsteps accordingly. the terrain stuff works great, the gameobject stuff not at all, it plays the sound of the terrain underneath the gameobject with collider even though layer name checks out.
does anyone here know why?

https://hastebin.com/share/tageguwula.csharp

spare island
#

yeah, but to be honest its very inflexible

#

the benefit to using playerprefs is that its persistent between installations

#

thats also its downfall, you usually dont want save files to be tied to windows registry

#

or whatever platform its on

#

yeah

#

its more flexible, convenient for you and for the user

#

you could also argue that for the use case of settings, if you want them to modify settings you could leave them in a plain json file

cold parrot
#

use json, anything else is extra work thats a pain to replace.

cosmic rain
#

Depends on what you mean by a "file type". If you mean the extension, it doesn't matter at all . You can even have extension less files and that wouldn't affect the contents of the file. Now the contents are up to you, but generally they're either in a text format(like json, xml or just plain text) or binary(which you'd need to know how to interpret otherwise it would just look like a sequence of 0 and 1).

calm mountain
#

Format!

chilly surge
#

If you foresee the possibility of format changing and you still need the ability to load older formats, you should also have some way to identify the format version. A common approach is to just have a version field in your content.

zealous vector
#

This is in update()

  //WorldPositionOfRayHit
  worldPos = GetMouseLookAtPos(Input.mousePosition);
  //Get the degree to face relative to player and ray hit
  float targetAngle = Mathf.Atan2(worldPos.x, worldPos.z) * Mathf.Rad2Deg;
  //TurnSMoothly
  float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
  //Rotate on y-axis to the degrees given by atan2
  transform.rotation = Quaternion.Euler(0f,angle,0f); 
#
 public static Vector3 GetMouseLookAtPos(Vector3 mouseScreenPos)
    {
        RaycastHit hit;
        //Cast a ray from mouse to world
        Ray ray = Camera.main.ScreenPointToRay(mouseScreenPos);
        
        //If it hits something return the place it hit it
        if (Physics.Raycast(ray, out hit))
        {
            return hit.point;
        }

        return Vector3.zero;
    }
wide terrace
zealous vector
#

yep that fixed it thanks!

grave otter
#

Hello, Im trying to update two different score vairables that are inside of a pause menu. I keep getting NullReferenceExceptions saying that the Object reference not set to an instance of an object even though I have done this. Please help!!!

vagrant blade
#

Make sure you don't have two of those scripts in your scene. Search the script name in your hierarchy.

grave otter
#

Legend!!! thank you so much!

spark stirrup
spark stirrup
leaden ice
spark stirrup
#

Alright

leaden ice
#

Debug.Log, and/or the debugger in your IDE

dense estuary
#

I'm experimenting with procedural animation, and I am trying to make this little worm guy, but I am having some trouble. Here is my script: https://hastebin.com/share/gesiqonufe.csharp. I think whats happening is the segments are folding in on themselves, is there a way I can prevent them from folding in on themselves, without making them collide with eachother?

#

Oh, my bad

empty elm
#

I recently learned that not unsubscribing to an event causes the subscribed object to not be garbage collected properly after its deletion.
I know this is bad practice since it doesn't free up unnecessary memory but my question is does it cause any unexpected behaviour in/after the deletion of the object? As far as I understand the reference to the subscribed delegate still exists and it gets called but it does nothing. I tested this scenario and nothing crashed.

next quiver
#

what does <> in class declaration mean ? e.g. public class Grid<TGridObject> { { }
is it related to generics?

empty elm
spark stirrup
#

If i'm running a script from the event trigger thats on another object how can I get the object that is calling the script?

indigo tree
keen lantern
#

Is anyone good with decoding error messages? Im not sure what this means or why I cant use this. The docs say that I can use Network Objects but its obviously still returning an error

#

(2nd image is a screenshot of the docs)

#

And for more info, the _nobPrefab is a network object
[SerializeField] private NetworkObject _nobPrefab;

spring creek
#

It wants a bool for the second parameter. It is called asServer

keen lantern
#

oh I see it now

#

I didnt know that it shows you what it needs

#

thats cool to know

#

thanks!

raven orbit
#

whats the difference with transform.Rotate and Transform.Rotate

indigo tree
#

It is just different target

raven orbit
#

oh okay, thank you

cosmic rain
#

That being said, Transform doesn't have a static Rotate method, so I'm not sure where you're seeing that.

raven orbit
#

I’m not sure what that means, I just got an error and changing Transform.Rotate with transform.Rotate fixed it so I was wondering

#

how do I start making things without tutorials, I’ve been trying but I just don’t know how to start I know nothing

cold parrot
raven orbit
#

thank you, I appreciate you for helping me

vale bridge
#

Does tweaking variables in the editor work because of reflection + serliazation? More specifically for the private variables I suppose

lean sail
#

i dont think theres really another way to get the list of fields that a class has

rough sorrel
#

Hi. When overriding a void, is it normal that even when using the base void, and in the base I do return, it still does what is in the override? Like for example, if I have the following:

 protected virtual void FixedUpdate()
    {
        if (!IsReleased || (ReplayManager.inst!=null&&ReplayManager.inst.ReplayPlaying))//this returns true, so it should do the return
 return;
}
protected override void FixedUpdate()
    {
        base.FixedUpdate();
//some more code here
}

And it is still running the part of "//some more code here", even tho it had a return in the base

lean sail
rough sorrel
#

Oh okay, I thought return stopped like that method from continuing executing. My bad. I'll have to find something else then

#

thanks

lean sail
rough sorrel
#

that wasn't the full code, it was just the part that was causing some problems, but yeah, otherwise it wouldn't make much sense😅

raven orbit
lean sail
raven orbit
#

i thought tutorials wouldn’t get me anywhere but I’ll take ur advice

#

thank you very much

lean sail
raven orbit
#

I’ve been trying to understand all the code but I’ll start experiment with it as well

cold parrot
#

The idea generally is that if you understand something once, it will be impossible to forget. If you forget you have not understood it.

raven orbit
#

most of the time it’s the math I dont get, I’ll keep trying though

cold parrot
#

Well, understanding math takes a lot of effort. Very few make that effort outside university.

raven orbit
#

I’ll try my best thank u for your advice

fickle birch
#

Hey guys

#

I'm trying to create a 2D Wall that starts off invisible but fades in to become opaque as the Player gets closer in its Trigger

#

Does anyone know a good tutorial for it? My code works but the problem is that when the Player is inside the Trigger the Wall keeps fading in from 0 to 1 alpha every time the Player presses an input

knotty sun
#

at a guess you woould want a raycast and a Lerp in OnTriggerStay2D

fickle birch
knotty sun
#

actually you dont even need the raycast, the Collider info can give you a distance

knotty sun
#

Vector3.Distance from the player to the collider and feed that into the Lerp

fickle birch
#

I didn't use a Raycast or Lerp, just a Coroutine that does this

wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, wallSprite.color.a + Time.deltaTime * fadeInSpeed);

#

Lerp and MoveTowards were giving me funky results

knotty sun
#

that will not work for 'less transparent the closer the player gets'

fickle birch
#

You're right, but I spent an hour+ on that problem so I'm happy this works lmao 😅

I'll try one last time with your method

fickle birch
knotty sun
#

yes, and you need to convert that into a value between 0 and 1 for the Lerp

fickle birch
#

  private void OnTriggerStay2D(Collider2D collision)
    {
        if (!playerInTrigger) { return; }

        // If the Player stays in the Trigger
        if (collision.gameObject.CompareTag("Player"))
        {
            // Calculate the distance between the Player and the Wall
            float distance = Vector2.Distance(collision.transform.position, transform.GetChild(0).position);
            // Calculate the alpha of the Sprite based on distance and maxDistance
            float alpha = Mathf.Clamp01(1 - distance / maxDistance);
            // Update the wall's color with new alpha value
            //  wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, Mathf.Lerp(wallSprite.color.a, alpha, Time.deltaTime * 5f));
            wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, alpha);

        }
    }```
#

Hmm, maybe I don't understand what you mean but when I used the above method, the input problem still existed and the fading out was instant while only the fading in was smooth

even though they use the same logic and I even tried a slower fading out than in speed

It's like the Wall reevaluates every time I press an input when I'm inside the trigger and starts fading in from 0 alpha again

knotty sun
#

look at it this way
onTrigger enter you have a player position and a collider position. this gives you a distance which is your total distance.
in on trigger stay you calculate the current distance between the player and the collider and then use that to calculate a factor of the total distance, 1 - that is your Lerp t

fickle birch
# knotty sun look at it this way onTrigger enter you have a player position and a collider po...

  private void OnTriggerStay2D(Collider2D collision)
    {
        if (!playerInTrigger) { return; }

        // If the Player stays in the Trigger
        if (collision.gameObject.CompareTag("Player"))
        {
        // Calculate the current distance between Player and Wall
        float currentDistance = Vector2.Distance(collision.transform.position, transform.GetChild(0).position);
        
        // Calculate the lerp factor based on the current distance
        float lerpFactor = 1 - Mathf.Clamp01(currentDistance / maxDistance); // maxDistance is a private var
        
        // Apply the calculated alpha
        wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, lerpFactor);

        }
    }```
#

oops

knotty sun
#

not sure why you need the Clamp currentDistance / maxDistance should never be > 1

fickle birch
#

True

#

redundant I guess

#

compiling

knotty sun
#

one problem is this
wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, lerpFactor);
you should have a startColour and an endColour not reuse wallSprite.color all the time

fickle birch
#

The input reevaluation still exists :/

knotty sun
#

but there is nothing there that deals with input so how?

fickle birch
#

I don't know, maybe it's because OnTriggerStay runs every frame or something, I'm not sure

knotty sun
#

that has nothing to do with input

fickle birch
#

Do you see any problem in the way I'm calling my coroutines

#
  private void OnTriggerExit2D(Collider2D collision)
  {
      // If the Player exits the Trigger
      if (collision.gameObject.CompareTag("Player"))
      {
          playerInTrigger = false;

          // Stop any ongoing fade coroutine
          if (fadeCoroutine != null)
              StopCoroutine(fadeCoroutine);
          // Start fading out the wall
          wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, 1f); // hard coding full opacity here because of funky behavior
          fadeCoroutine = StartCoroutine(FadeOut());
      }

   private IEnumerator FadeOut()
   {
       // Gradually decrease the alpha value to fade out the wall
       while (wallSprite.color.a > 0f || (playerInTrigger == false))
       {
           // wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, Mathf.MoveTowards(wallSprite.color.a, 0f, Time.deltaTime * fadeOutSpeed)); // Faster fade out
           wallSprite.color = new Color(wallSprite.color.r, wallSprite.color.g, wallSprite.color.b, wallSprite.color.a - Time.deltaTime * fadeOutSpeed); // Faster fade out
           yield return null; // Wait for the next frame
       }
   }
  }```
knotty sun
#

apart from the facxt that it should be using the Lerp factor last calculated in Stay to go back to zero and the same incorrect usage of wallSprite.color, no

fickle birch
#

Sorry I forgot to update that, but I'm not sure it will solve the input issue

knotty sun
#

but this has absolutely nothing to do with input so I don't see where that can come from

fickle birch
#

the distance dependent opacity would be a bit fancy anyway

#

#copium

knotty sun
#

It's really not that difficult and is a quite common mechanic

fickle birch
#

I know 🥲

#

I've done it Unreal

knotty sun
#

yeah, but I bet you just used blueprints rather than writing the bare C++

fickle birch
#

No lol, it was C++ but I admit I followed a tutorial

worn star
#

is there anyway for an animator event to call a function in a script not attached to the same object

somber nacelle
#

pretty sure the answer to that is "no" but you can always have the animator event invoke some method that invokes another event that your other objects can subscribe to

amber depot
#

Guys I am trying to play a video via Video Player component on a 2d canvas, I am using a basic lit URP mesh rendered material (color: white). As soon as I press the button to display the video, it still remains white. I can hear the voice but nothing show up and am getting this debug.log "Unexpected timestamp values detected. This can occur in H.264 videos not encoded with the baseline profile. Timestamps will be skewed to correct the playback for C:/Unity/OKI! Friends/Assets/Voicecall Video/Demo_Video_NEW.mp4"

#

I have not transcoded the video in unity still as the codec is already H264

mental orchid
#

For unity localization package, how can I get the percentage formatter {x:0%} to work correctly? or do I have to implement my own custom formatter for this?

sweet current
#

Help me:
I did...something and now when i want to select and move objects i can hover over all vertices instad of having the object selected.

  • What is that called?
  • How can i disable that?
  • if i hold ctrl the transform-gizmo is set to the pivot of the object, ...i think i accidentally activated something
leaden ice
#

Probably ProBuilder vertex mode

#

Switch back to Object mode

#

(this screenshot is too zoomed in/cropped)

#

Also this isn't a code question

gray mural
#

What would be the correct way to make a Texture, used in the custom Editor's GUILayout.Toggle's GUIContent, smaller, as it is displayed with its original size? Does copying the Texture and changing its size sound fine? If so, what would be the most suitable way to do this?

leaden ice
gray mural
leaden ice
rustic temple
#

hi! i'm trying to build asset bundles on apple arm, i'm using this:
BuildPipeline.BuildAssetBundles(assetBundleDirectory, BuildAssetBundleOptions.None, BuildTarget.StandaloneOSX);
but i think StandaloneOSX only supports intel

#

is there anyway to get arm working?

gray mural
loud wharf
#

I wonder if once unity moves to coreclr, do we still have to deal with assembly reference files and unity overwriting every cs project files?

topaz hinge
#

speaking about Unity's Localization tool... is there a way to know whether a LocalizedString that contains other LocalizedStrings as values for its variables is ready?

I came across this problem yesterday, in which my localized string would just print an empty string instead of the localized string value it contained... I tried running RefreshString() over and over, but it would return false every single time... I had to subscribe to the StringChange event, but it was kind of a bummer to do lol... I would have preferred to have a coroutine to wait until it is ready and then set the value (I know it wouldn't update if I change the language, but I can handle that)

sweet current
full gorge
#

Anyone that knows a bit about serialization available to help a bit?

full gorge
#

I am setting up a save/load system in my game and having some doubts about the reliability. My game data is stored in a single, "master" C# class (not monobehaviour nor scritableobject) named GameState. I can serialize it all without any issues using JsonUtility, and it SEEMS to be working alright for now.

For other normal serializable classes, all the relevant data is there and it seems to be OK.

Now, when I get to ScriptableObjects, things are looking a bit iffy. I know already I cannot serialize the SOs themselves, this is not what I am trying to do. What I am trying to do is just store the references to them in my save file so when I load the game, they get put back in their positions. This SEEMS to be working for now, but the save file has "Instance_ID"s for each, and those are NOT permanent, right?

I looked around a bit and only found some really old posts talking about that. Do any of you know if any recent unity update fixed that behavior somehow or if this is still an issue?

What are my options here? Dropping SOs and using normal classes for all serializable data? Or setting a dictionary so jsonutility saves and loads them with "other names" in order to make it work properly? The second approach would be a bit complicated because my SOs are quite spread around in my data tree.

full gorge
leaden ice
#

you need to have your serialized data reference the SO asset in a different way

#

For example by name to use with Resources.Load

#

or with an Addressables Asset

#

or with some custom identifier you make that you know how to resolve to an actual reference

full gorge
#

Yeah, that's what I thought. Dang it. If JsonUtility just got the GUIDs of the assets it would be so much simpler T.T

#

I see

leaden ice
#

or, yes, drop SOs in your serialized data entirely

full gorge
#

Got it. Either drop SOs or transform their references into something else and manage a way to put them in their slots when loading.

#

I will look into the addressables, maybe. Because I've read "resource.load" can be a bit bad performance-wise?

#

I thought about just creating a dictionary of all my SOs x Unique identifier but I have no clue of how to make the game read that and find the assets (beginner here). The closest to that would be Resources.Load, correct?

leaden ice
#

yeah you could do that. basically something like this (contrived example):


[Serializable]
public class ItemData {
  [SerializeField] private string itemId;

  public ItemSO GetItemSO() {
   return ItemDictionaryManager.Instance.GetItem(itemId);
  }
}```
knotty sun
#

An Array may be better, if the SO's inject themselves into a fixed index of the array and the reading classes read from that index it's just a case of storing an int on both sides

full gorge
full gorge
leaden ice
#

the problerm with a list or array and depending on index is that you can't ever rearrange that list or array or remove things from it

knotty sun
full gorge
#

So then the SOs will be organized such as "Armor[1]", "Character[5]" and so on, always being unique.

#

True

full gorge
#

Removing breaks everything

#

Didn't consider that.

full gorge
knotty sun
#

yes, but you wont be creating new so's at runtime will you

full gorge
#

Not at all

knotty sun
#

so fixed size is not a problem

full gorge
#

Hmm... I can make it generate for every SO of a type within the contents folder and it will have the exact size always, right? However... What if I ever remove an object like Praetor mentioned? The other slots won't "move" but that one will be left empty correct? Would a dictionary be better with that? Or just setting an UID inside the SO itself and making the game read it and look for that when populating the slots?

knotty sun
#

tbf you could implement the Dictionary approach for ease of development and switch to an array for production. The change would be trivial

full gorge
#

That makes sense. While I am changing stuff keep it all as a dictionary to avoid messing up and then when stuff is more set in stone, change to an array.

#

But how exactly do I integrate any of those approaches with the serialization/deserialization process? The serialization is actually straightforward, my issue is with the deserialization.

#

How can I make the engine populate the SO slots with the original SOs after it reads those unique identifiers?

knotty sun
#

you just need to store the itemid on both sides

full gorge
#

Hmm... I don't quite follow. Which sides you mean?

knotty sun
#

well on the so itself and the classes using the SO's

rugged goblet
#

Just use a dictionary, no reason for an array

knotty sun
#

Then you have code in the OnEnable of the SO so it injects itself into the Dictionary

rugged goblet
#

Use a human readable ID rather than an index, you'll save yourself so many headaches

full gorge
#

Yeah I think a dictionary is simpler for me especially since I am kind of a beginner still. But if performance is worse or something, I don't mind learning.

rugged goblet
#

The performance difference is miniscule

spring creek
full gorge
full gorge
#

Love this approach. Will make it really uniform and straightforward (useful so I don't get swamped in complicated logic lmao

full gorge
knotty sun
#

your dictionary can be static or attached to a singleton just to make life easier still

rugged goblet
#

Most importantly, your dictionary doesn't depend on some abstract order

full gorge
#

Yeah, the methods I was trying to come up with would put those "onenables" on every class that had SOs, that is why I was considering just dropping SOs altogether lmao

#

And actually, base C# classes don't even have onEnable.

#

So it wouldn't even work. But putting OnEnable methods on all SOs that go into serializable classes is WAY easier and uniformizable. You saved my life there @knotty sun! Thank you VERY much!

rugged goblet
#

If your weapon data is just represented on a ScriptableObject, I wouldn't necessarily do that approach...I would use POCOs and serialize them to a file to be loaded at runtime

spring creek
rugged goblet
#

Sorry, Plain Ol' C Object

#

Just a basic normal object

spring creek
full gorge
#

Oh! You mean using base C# classes, right? Got it. Yeah I thought about that as well, but having the ease of creating new weapons as separate assets and handling them in the inspector and having the data preloaded into the game on starting is so useful.

#

But yeah, it is also an option, of course.

#

It's just that being a newbie in unity, the more "visual" approach of the SOs really caught me. But if setting them up becomes a nightmare I can just keep serialized stuff away from them and use them only for permanent stuff.

rugged goblet
#

Yeah, it's probably more work than it's worth for you, and the overhead from the ScriptableObjects is negligible in the grand scheme of things

full gorge
#

And the solution Steve offered should work like a charm too! I will try it out now.

#

Then again... OnEnable is called when an object is enabled, right? SOs get enabled when the game loads so would it actually work like that?

knotty sun
#

and build the soDict as part of the Deserialization operation

full gorge
#

I see... I will explore those and report back when I manage to implement. It would be so good if JsonUtility just used GUID instead of Instance_IDs though... lmao

knotty sun
full gorge
#

Oh, dang. Yeah, so nevermind ahahaha

I am trying to implement the dictionary in a way that it actually "works" during the serialization/deserialization so the class it returns is just right from the get go to replace the "old" one.

#

If this works the problem is solved. If not, I will try the other approaches.

robust mantle
#

This is my script for that:


        float angle = Mathf.Atan2(target.transform.position.x - transform.position.x, target.transform.position.z - transform.position.z) * Mathf.Rad2Deg;
        if (angle < 0)
            angle += 360;
        transform.eulerAngles = new Vector3(transform.eulerAngles.x, Mathf.Lerp(transform.eulerAngles.y, angle, lookLerp), transform.eulerAngles.z);
#

^ If i dont do the angle < 0 statement it spins around in circles since its a negative angle and kinda fks up so if you know a solution to that too thatd be nice

full gorge
#

Serializing classes with Scriptable Object references

  • UID Dictionary: Set a dictionary to store all SOs and their respective UIDs. This will be populated on Awake of the GameManager object by a populating method that fetches all SOs currently referenced in the game for use during saving and loading the game.

  • Saving: Call the SaveGame() method in which a copy of the current GameState is instantiated and processed by replacing all SOs by their UIDs from the dictionary. With that done, run the JsonUtility to serialize.

  • Gameplay: You can play the game as normal, since the original GameState has not been modified.

  • Loading: Call the LoadGame() method to deserialize with JsonUtility as usual, then substitute the UIDs everywhere in the GameState with their corresponding SOs (SO subtypes are kept). Finally, replace the current GameState with its processed version.

And done, the SO references will be kept in a more secure way instead of using Instance IDs.

#

Thanks a ton to everyone that helped! ❤️

meager timber
latent latch
plucky heron
#

Does anyone know how to script bullet shell and mag removal system. Also I am working on a bullet trajectory calculator and in it the physical properties get calculated and saved in a file. I want to know how to access and write files in unity

knotty sun
cold parrot
steady moat
#

Neither.

grizzled ibex
#

Rust is pretty great from a performance perspective for what it has

#

I can't speak for EFT

steady moat
#

Are they even bad ? For what they offer at least.

grizzled ibex
#

But regardless, optimization is complicated

#

It has nothing to do with poor programming or Unity, it's just hard full stop.

steady moat
#

For you ?

grizzled ibex
#

I don't remember having many issues with EFT, might be your specs

steady moat
#

Everyone that complains*

lean sail
#

If it was barely playable then no one would play it

grizzled ibex
#

Negative voices are always the loudest

steady moat
#

Classic Survivor bias

grizzled ibex
#

Check your thermal procs and bottlenecks

steady moat
#

So, it runs.

simple egret
#

Do you have a programming, Unity specific question? This channel/server isn't the place to ask questions about solving problemns in games you did not make

steady moat
#

What is the issue to give better performance for future or better specs

#

Go on Reddit, if you want to make a hate thread about things you do not know.

grizzled ibex
#

Regardless we can't know what's wrong with rust/eft as we don't have the source 😛

#

It's definitely not Unity at least

simple egret
#

No it's just off-topic for this server

steady moat
#

What question ?

lean sail
#

You didnt ask anything unity related

grizzled ibex
#

Who took what personally huh

feral bronze
#

😂

simple egret
#

They're not wrong, though, this isn't the place to complain about built Unity games

vagrant blade
#

Nobody can answer your question here, as nobody here is the developer of the games you're having issues with.

simple egret
#

So, the answer to the question is : you can't know. Only developers will have access to the profiling tools

vagrant blade
#

This is purely a development server for people using Unity to make their own games. Any questions/issues you have with existing games isn't suited for this server.

#

You may want to ask them directly in their community discords, if they have them.

#

See ya

grizzled ibex
#

That was an expert level troll

vagrant blade
#

Inb4 they go to whatever community they want to annoy and say how "I got them good!"

lean sail
#

Well im guessing unity wont be their engine to learn anymore

spring creek
vagrant blade
#

!kick 431519822203977739 Seeing that you couldn't help but return, I'll help you out: no need to return if you're not here for Unity development questions/discussions.

tawny elkBOT
#

dynoSuccess mynde was kicked.

spare island
#

!code

tawny elkBOT
spare island
#

Goal: Animation plays when LoadingScreenWillDeactivate is invoked from LSM
Obstacle: LoadingScreenWillDeactivate (L33) seems not to be invoked, but @L31 - @L34 do execute. I'm assuming it's not being invoked because in AC @L15-@L16 do not execute. Placing a breakpoint on L33 has no result, it does not break.

AC (Animation controller)
https://hatebin.com/kojnlgbkfc

LSM (Loading Screen Manager)
https://hatebin.com/oqtcqjvlda

#

I think the most likely issue is the Destroy call, but the call is delayed and shouldn't stop the delegate invocation anyway
edit: removing the destroy call does nothing. the loading screen is not destroyed and the animation still does not play

#

even then i'd expect the invocation to succeed but to get a "this object is destroyed" error on the animator

#

There are no exceptions

#

animator is not null and animator does have bool 'IsDone'

#

oh wait i think i figured it out? i think my service getter wants me to use ILoadingManager instead of LoadingManager

#

nope

#

its returning the service so it should be subscribing to the event fine..?

#

maybe interfaces dont like events..? i don't understand

#

Event not being invoked

somber tapir
#

Setting the rotation with t.eulerAngles = someVector3 causes the object to sometimes flip 90° on a direction that shouldn't change at all.

What should I use instead? I tried t.rotation = Quaternion.EulerRotation() but that seems to be deprecated.

mental solar
leaden ice
#

As for memory leaks - use the memory profiler

spare island
#

bruh ghost ping

mental solar
#

fair enough, just not sure about the behavior of dynamically allocated resources (new Texture2D and Sprite.Create)

#

I am supposed to destroy them manually?

iron vortex
#

Does anyone know how to pass a reference to a MonoBehavior method to a static function so that I can call a coroutine from within it?

hidden flicker
#

How do I store the changes made to a scene during runtime into the scene file itself?

merry surge
#

i am very confused by transform.TransformDirection

if my transform's rotation euler angle is 0,90,0 and i do TransformDirection on an euler angle of 0,270,0 the output is still 0,270,0

spare island
spare island
#

to a monobehaviour to a static function is confusing

iron vortex
#

Sorry it turned my brain to mush

#

Basically I need to call a coroutine from within a static function, but you can't do that normally because it needs some kind of reference to an object that's under MonoBehavior

#

idk how to do that in code

#

well I've tried a few ways

hidden flicker
naive swallow
spare island
hidden flicker
iron vortex
iron vortex
#

I guess the script instance itself

naive swallow
#

Which instance

#

you could have this script on a trillion objects for all it knows

spare island
grizzled ibex
lean sail
#

As long as you arent using BinaryFormatter specifically, it's fine. The only downside (or upside if you dont want users editing it) being it's not human readable

iron vortex
# naive swallow _Which_ instance

Well, this script instance only exists on just one object, so I tried to pass it through with this but I doubt the reference stays consistent

naive swallow
iron vortex
#

That is a good question

spare island
grizzled ibex
#

I understand the latter 2 but how is it insecure? That's the first I'm hearing that

#

Just genuinely curious!

spare island
#

BinaryFormatter has a well known RCE

#

Microsoft itself heavily discourages using it if you can

grizzled ibex
#

Jeez thanks for the headsup

#

I was not aware of this

spare island
#

On the plus side you can give your game free mod support

#

Lmao

lean sail
#

There are alternatives, which are listed in the same page. Writing binary itself is not an issue

spare island
#

Right, but binaryformatter is the thing most beginners hop to (besides player prefs)

#

And the other two reasons still apply

grizzled ibex
#

I think it's because Unity literally uses it as an example for serializing in some of their tutorials

#

that's very questionable

naive swallow
#

The general process of using a formatter to serialize and deserialize data are pretty transferrable

#

Just don't use this specific formatter

grizzled ibex
lean sail
#

Could be a very old tutorial before the risks were known

spare island
#

I also used to use bf until I swapped to easy save which uses json

iron vortex
naive swallow
iron vortex
#

it exists on an object that arbitrarily is registered and sometimes destroyed conditionally

#

so I had to do that to make the references consistent

spare island
#

Service locator?

naive swallow
#

So there's no reason for this function to be on the class instead of an instance

spare island
#

You probably want a singleton

iron vortex
#

Huh, okay that'll take me a bit to wrap my head around

#

Idk

#

The point of this is so that I can disable a fade-in gameobject so that it doesn't overlay over the other UI elements** **

#

my solution to this in other cases has been a coroutine to disable the object once the animation finishes, and I know there's more than one way to solve this

#

however as you know it's in a static function in the controller class

minor patio
#

how to make weapon sway for 2d

#

without animation

rigid island
#

use something like sin functions

#

depends how you want it to sway

wide terrace
#

or an AnimationCurve, if you want a little more control

minor patio
dark sparrow
#

Why am I never getting this done the right way regarding Layers.

if (collision.gameObject.layer == projectileData.layerDetection)

Doesn't work properly how am I supposed to do the if line?

somber nacelle
#
  1. a gameobject's layer is not a layermask, those will not be equal to each other
  2. why are you trying to compare the layer in the first place?
dark sparrow
#

I just want the projectile to only react to objects that have the Player layer.
How am I gonna do that then? When I just type in the number it works, but I want to be able to set it through the inspector and not static

somber nacelle
spring creek
dark sparrow
#

Yeah I see its using bits, thanks for your answers I will have a look

merry surge
#

i am confused by transform.TransformDirection

if my transform's rotation euler angle is 0,90,0 and i do TransformDirection on an euler angle of 0,270,0 the output is still 0,270,0

#

it should be 0,0,0 shoudl it not?

lean sail
#

In which case both the transform up and vector3.up align

merry surge
#

Oh it's supposed to use normalized vectors?

#

It didn't really specify that

lean sail
#

The object has no rotation on its X or Z. Its local up and world space up are the same

merry surge
#

Basically, I have a game object rotated 90 degrees about the Y axis and I want to determine what the local rotation of 0,270,0 is in worldspace

#

The result I need is 0,0,0

#

Maybe I'm just going about reaching that value incorrectly

lean sail
#

If the object has no parent, its local rotation is gonna be the same as the world rotation

main oxide
#

i really need help i deleted my oculus folder cus i got compile errors from the all in one sdk meta and now i got 209 compile errors

merry surge
#

I have a local object rotated 270 degrees I mean

lean sail
main oxide
#

now when i open unity i only got 5 errors but everything is pink and i cant find the rendering tab to make it not pink

merry surge
#

I have a sub position I calculate in this game object that's rotated 90 degrees

#

The sub position also has a rotation

#

So like, if the object rotates then I need to apply it's worldspace rotation to the local rotation value when I compute the position and rotation

#

Basically I want to take 0,90,0 and add 0,270,0 to it

lean sail
#

Could you not just use a child gameobject and have this done automatically?

merry surge
#

Long story but no, this is all computed data

#

It shouldn't be difficult, I'm basically just using the transform to convert that local position and rotation to worldspace

#

But the function I'm using seems to not do what I need

#

Converting the sub position to worldspace was easy

#

But this rotation function isn't giving the expected value

lean sail
# merry surge But this rotation function isn't giving the expected value

I dont really see whatd stop you from still using a child game object and just reading off those numbers. But yea the issue is what I said above. The method you're using is expecting a direction.
Though what's stopping you from just doing what you said above, adding the 2 vectors of your euler angles?

merry surge
#

Maybe that's the correct way to do it, I just assumed that function was the right way

#

If a game object is rotated 0,90,0 and I transform a local angle of 0,270,0 then should it not add 90 to Y?

lean sail
#

That function would be more like "I want my object to move forward relative to itself but I wanna specify (0,0,1)"

lean sail
#

If your sub object is supposed to be rotated 90 degrees relative to the game object then yes just add the 2 vectors.

robust mantle
uncut palm
#

its not exactly code but it is coding related...

i dunno when it started, but all of a sudden I cant edit the middle of a line anymore in visual studio, i can only replace letters from left to right if i want to add something, a bit like command prompt

anyone know how to disable this?

somber nacelle
#

press the insert key

uncut palm
#

W thanks

shell scarab
#

So now that all the forum links are broken, is there a way to find those posts on unity discussions? Tried looking up the exact title but couldn't find the post.

rigid island
shell scarab
#

it says that the migration is "fully complete" D:

rigid island
#

maybe links didn't propagate or update dns yet

worldly hull
#

so the only problem will be

  • is color32 converted completely empty
  • other possible reason that is blocking the setpixel or apply
rigid island
#

I meant post it here seems to be code related

#

I didnt read the whole thing yet

#

i got adhd lol

cosmic rain
worldly hull
#

hold on lemme test one last thing

grave otter
#

Hello, I am having trouble with audio in my 2d platformer. I have two scenes with different music playing in them. My Menu Audio Manager should be destroyed when a new scene is loaded but it stays resulting in both sets of music playing at the same time, please help!!

worldly hull
#

i found out the problem , thx

#

👍

spark stirrup
#

I have a button that I want to run a method in a script on another object when clicked, problem is that that method takes 4 parameters and button ``onClick()` only allows for methods with at most 1 parameter

#

anyway to get around that?

rigid island
#

don't think if you want to use inspector

spark stirrup
#

Dang I'm making a crafting system and I want it to be as dynamic as possible so i didn't want to hardcode recipes

rigid island
#

You could probably wrap it in another method

spark stirrup
#

how so?

rigid island
#

using delagate with AddListner

spark stirrup
#

how hard would it be to make recipes loaded from a json file?

rigid island
#

I'm trying to remember it rq, I havent used inspector for this in a while

#

not hard at all

spark stirrup
#

Maybe I should just do that then

rigid island
#

yeah imo thats clean and easy to even update remotely

spark stirrup
rigid island
spark stirrup
rigid island
#

just a regular class (Plain Old Class/Clr Object)

#

like cs public class MyClass { }

spark stirrup
#

ohh alright

spark stirrup
golden ibex
#

Hi, there. I'm attempting to create a first person controller with 6 degrees-of-freedom movement in a zero-gravity environment. I have a camera holder that moves to a specified empty child of the player object with LateUpdate. I am translating the player's rigidbody with AddForce and rotating the rigidbody with MoveRotation with FixedUpdate. (I was initally rotating the player's transform directly with transform.Rotate.)The translation works great, but the rotation causes camera jitter. The jitter is especially noticeable when translating and rotating at the same time.

My understanding is that camera jitter on a rigidbody player controller is very a very common issue for beginners. I've tried following quite a few guides on Youtube, the Unity forums, and Reddit. So far, nothing has worked. Many fixes I'm seeing don't apply to me because of my unique camera set-up and movement system. My intention is for the mouse input + roll keys to rotate the entire player object, so a traditional FP controller setup does not work for me.

Thing's I've tried: The rigidbody's interpolation is turned on and I have tried both settings for it. I have tried changing the camera holder move script to FixedUpdate and regular Update. I have tried making the camera update move and rotate to the rigidbody instead of the player's transform. I have also tried making the camera a direct child of the player object.

All three of my C# classes: https://gdl.space/yokesabive.cs First one handles the rotation inputs and applies rotation to the player's rigidbody. Second one handles translation. Third class is on the camera holder and updates its own position to be that of the player's position. (The main camera is a child of the camera holder.)

Screenshots of my editor setup are attached.

indigo tree
golden ibex
#

I am unfamiliar with the concept of constraints on a camera beyond a MathF.Clamp on a camera's rotation

indigo tree
golden ibex
#

Thanks, I understand now. I was unaware of constraint components. I'm testing it now.

golden ibex
#

I've now set up the constraint components and it seems to have reduced the amount of camera jitter significantly. There's still way to much for the kind of game I'm making, but now that I know about constraint components I'm going to give another technique a try.

spark stirrup
#

I have a variable i want to set: inventory.wood but I don't want to write a separate line fo code for each object. Would I be able to pass in a string instead of wood? So something like inventory.(this.blockName)?

spark stirrup
rigid island
spark stirrup
#

I'm trying to access a variable of another script so that I can set another variable to match it

rigid island
#
    public void ChangeResource(Resource resource)
    {
        theResource = resource;
    }
    private void Hi()
    {
        ChangeResource(Resource.wood);
    }```
spark stirrup
#

I did some research on enums. Is it true that I can only hard code their values?

rigid island
spark stirrup
#

this is what I'm trying to do essentially:

private void Start()
{
        
    associatedPrefab = Resources.Load<GameObject>("Prefabs/Building Blocks/" + blockName);
    UpdateText(associatedPrefab.GetComponent<BlockAmount>().amount.ToString());
    if (GameObject.FindGameObjectWithTag("Inventory"))
    {
        GameObject inventoryObj = GameObject.FindGameObjectWithTag("Inventory");
        switch (blockName)
        {
            case "Log":
                amount = inventory.wood;
                break;
        }

    }

}```
rigid island
#

jesus this is already overconvoluted

spark stirrup
#

inventory.wood is an integer

rigid island
#

so you're trying to do an inventory count?

spark stirrup
#

I know I shouldv'e used a dictionary but i'm too far along to switch to one

spark stirrup
rigid island
#

then yes use a dictionary..

spark stirrup
#

I have 2 scenes with 2 different inventory implementations and I need to keep them consistent

rigid island
#

what does have to do with dictionary

spark stirrup
#

easy to pull values from

#

or easy to look up values i mean

rigid island
#

using a switch for this when you can easily do it in 1 line with dicionary

spark stirrup
#

Yeah that's what i'm saying, a dictionary would be better. I just don't want to use one because i'd have to rewrite a lot of stuff

rigid island
#

the way you're doing it now is not good and not very scalable.. rewriting code is part of the work

spark stirrup
#

It shouldn't need to be super scalable, it should work for what I need it to]

rigid island
chilly surge
#

It's tempting to "let the future me deal with it" but if you foresee your future self saying "this has gotten so bad that I can no longer continue working with this code and need to refactor it, I should've just done it two months ago and saved a bunch of time during the two months" then you might as well do it now.

knotty sun
#

what takes a day to fix now could take a week or more to fix in the future

chilly surge
#

Tech debt rarely shrinks by itself 😄

restive cradle
#

This missing reference is eating my head, Basically this only comes sometimes, if i add some debug or something in the code and run again its not coming, also in the build its not happening, only in the editor its happening, Is there any fix for this or has any one faced this before? please help.

Error:
MissingReferenceException: The object of type 'UI_References' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.MonoBehaviour.StopCoroutine (UnityEngine.Coroutine routine) (at <2d8783c7af0442318483a199a473c55b>:0)
UI_References.SetLoadingScreen (System.Boolean status, System.String msg) (at Assets/UI_References.cs:111)
LoginManager.Init (System.Boolean isTestUser) (at Assets/LoginManager.cs:102)
GameConfigurationManager.ApplyRemoteSettings (Unity.Services.RemoteConfig.ConfigResponse configResponse) (at Assets/UI Manager/GameConfigurationManager.cs:101)
Unity.Services.RemoteConfig.ConfigManagerImpl.HandleConfigResponse (System.String configType, Unity.Services.RemoteConfig.ConfigResponse configResponse) (at ./Library/PackageCache/com.unity.remote-config-runtime@4.0.2/Runtime/ConfigManagerImpl.cs:553)
Unity.Services.RemoteConfig.ConfigManagerImpl+<>c__DisplayClass46_0.<DoRequest>b__0 (UnityEngine.AsyncOperation op) (at ./Library/PackageCache/com.unity.remote-config-runtime@4.0.2/Runtime/ConfigManagerImpl.cs:542)
UnityEngine.AsyncOperation.InvokeCompletionEvent () (at <2d8783c7af0442318483a199a473c55b>:0)

quick delta
#

How do I actually "save" values with ScriptableObject?
I have one that get filled by a [ExecuteInEditor] script, and while I can read it perfectly it get reset to null everytime I load a new scene or restart the editor.
Tried AssetDatabase.SaveAssets, but it's not doing anything so I'm kinda confused on how to do it.

knotty sun
quick delta
#

I didn't even knew that was a thing.
Tested it and it look like that did the trick.
Thanks!

main oxide
#

bro my entire project is fucked for some reason uninstalling 1 folder corrupted my project cus when i go in to the project all my plugings are gone it uninstalled all my FUCKING stuff like xr pluging manament and all and it removed all my scripts and for some reason my fucking map has a skinned mesh render now and i cant restore it

lean sail
main oxide
#

i am

lean sail
#

Then you'll have to be more specific, probably in a different channel though because this doesnt sound like it's anything code related.
If you have version control then you can simply just go back to an earlier commit where everything was fine or even redownload the project if needed from that commit

main oxide
#

bro i dont know how

#

i got unity version control but i dont know how to go back versions

#

i dont even got the tab for it

#

it uninstalled it

lean sail
#

I dont use unity vc, have you googled anything related to that? And have you even made commits ever for it

main oxide
#

all my plugings tabs are gone

#

sould i seek help in xr hub

lean sail
# main oxide sould i seek help in xr hub

I dont really see how anything you said was XR specific so I dont know. I strongly suggest you look online for how to use or find your unity version control so you can see if you can revert. Though if nothing was ever committed then you dont really have something to revert to

inland moon
#
                using (var memStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("bundle1"))
                {
                    if (memStream != null)
                    {
                        MelonLogger.Msg("memStream is not null");
                        byte[] byteArray = new byte[memStream.Length];
                        memStream.Read(byteArray, 0, byteArray.Length);
                        MelonLogger.Msg($"ByteArray length is: {byteArray.Length}");
                        assetBundle = AssetBundle.LoadFromMemory(byteArray);
                        var prefab = assetBundle.LoadAsset("test", Il2CppType.Of<GameObject>()).Cast<GameObject>();
                    }
                    else
                    {
                        MelonLogger.Msg("memStream is null :(");
                    }
                }

What here could cause prefab to be null?

somber nacelle
#

perhaps you should ask in the community for the game you are modding, or in the mod loader's community

somber nacelle
inland moon
#

Alright

rocky tide
#

Hello. I have again come here and seek answers from the gods of the unity community to help with my problem. my console says after shooting the raycast LineRenderer.Setposition Index Out Of Bound. Any good tricks to fix this?

knotty sun
rocky tide
#

Oh i got it

#

I called a High Priest of Unity programming and got an immediate answer

knotty sun
#

not really, just someone who can be arsed to RTFM

keen forge
#

Sometimes when i hit play button in editor, it infinitely stucks on reloading domain. Recently i discovered that is happens only when PC connected to internet. Without internet connection everything is fine 🤷‍♂️ How to fix it? My current version is 2023.2.5f1 but i tried a lot of different versions so i assume problem is in my project. ChatGPT 🤖 adviced me to figure what of my assets can use internet connection by searching words like "www" "http" and other in project, but i didnt find anything like that notlikethis

gloomy path
#

does anyone know how to make a line renderer thin out over time?

knotty sun
gloomy path
#

wrong video oops

leaden ice
#

yes, use the width curve

gloomy path
#

oh alr thanks

keen forge
knotty sun
keen forge
#

no

knotty sun
#

then I would suggest you either move to the latest Unity 6 preview or regress to the latest 2022.3 LTS. If you regress create a new project with the editor version and use asset->export asset->import to migrate your project

keen forge
#

i tried a lot of versions, including 2022.3 LTS, unfortunately i had same problem on it

knotty sun
#

interesting, did you check the editor !logs to see if anything odd was happening?

tawny elkBOT
#
📝 Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

keen forge
#

yes, i checked it, but didnt get what it says, i am bit dumb( but i tried to compare logs with and without internet and didnt see difference

knotty sun
#

next time it happens, post the log to a paste site and ping me then I'll take a look

final forge
#

can any one help me with this script : using UnityEngine;

public class jumpscarestranger : MonoBehaviour
{
public float maxRaycastDistance = 10f;
public Transform playerCamera;
public LayerMask interactableLayer;
public MonoBehaviour playermove;
public Transform target;
public AudioSource audioSource;

void Update()
{
    // Create a ray from the camera's position along its forward direction
    Ray ray = new Ray(playerCamera.position, playerCamera.forward);

    // Check if the ray hits an object on the specified layer within the max distance
    if (Physics.Raycast(ray, out RaycastHit hit, maxRaycastDistance, interactableLayer))
    {
        audioSource.Play();
        playermove.enabled = false;
        playerCamera.LookAt(target);
    }
}

}

#

this when it look at the interactableLayer it just turn to target without activate the sound

knotty sun
#

you are starting the audio EVERY frame

final forge
#

ohhhhhhhhhhhhhhhhhh

#

tysm 😢

knotty sun
#

also when someone shows you a bot message READ IT

final forge
#

bot msg ?

knotty sun
final forge
#

ohhhhh sry bout that

loud pagoda
#

wow, i needed to make a batch file, haven't made a complicated one in over 20 years and forgot most of it ... microsoft's copilot (chatgpt thing?) basically held my hand through the whole thing, and when i had syntax errors, i pasted the whole code into it and asked how to fix it, and it very accurately fixed my errors as well as explaining what was wrong ... geez

knotty sun
fickle birch
#

Hey guys

#

I'm trying to create a Laser Trap that tracks the Player's position and rotates accordingly

#

It does that, but the problem is that

#

I want it to scale depending on the Objects it hits. So if the Player is under a platform, its Collider and Sprite should shrink so that it's hitting the platform, and then scale up again when the Player is in an open area. I do not know the right way to implement this.

But the tracking and rotating of the Purple Block itself is working correctly.

knotty sun
#

will you please learn to type in full sentences

fickle birch
knotty sun