#archived-code-general

1 messages Β· Page 132 of 1

rugged storm
#

Thank you

fluid lily
#

And people wonder why I have started separating my code from editor scripts...

[ShowIf(nameof(loadSettings) + "." + nameof(LoadSettings.IDType), SceneIDType.byName)]
    public string sceneName;

    [ShowIf(nameof(loadSettings) + "." + nameof(LoadSettings.IDType), SceneIDType.byID)]
    public int sceneID;

    public LoadSettings loadSettings;
    [Serializable]
    public struct LoadSettings {
        [ShowInInspector]
        public LoadSceneMode LoadMethod { get; set; }
        [ShowInInspector]
        public SceneIDType IDType { get; set; }
        [ShowInInspector]
        public SceneLoadType LoadType { get; set; }
    }```
#

Working on a code generator that creates wrapers from interfaces, will also be able to put default attributes where I set them to show up.

swift falcon
#

why is there an error

quartz folio
tawny elkBOT
#
πŸ’‘ IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

β€’ Visual Studio (Installed via Unity Hub)
β€’ Visual Studio (Installed manually)

β€’ VS Code*
β€’ JetBrains Rider
β€’ Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

swift falcon
#

but I already installed via unity hub

#

nvm

#

i have to configure

#

@quartz folio i dont get it, everything is alrd set

#

fixed

bitter finch
#

Is it possible to do web gl unity with 3d/2d avatars, text to speeh + animations? I see some mixed bags of features but nothing that's quite there yet

#

Sorry w/AI

swift falcon
cold egret
#

- Can i precalculate width of a configured tmp text based on a string on condition, that the string fits the resulting width? I.e. know how wide the text should be to fit the string inside

lean sail
magic quiver
#

hi guys idk if you guys know how to fix this but my VS is rlly weird

like there arent any red squiggly lines under anything ever and some things arent coloured, or arent autofilled if i press tab or enter or something

#

also ik this isnt rlly a unity issue but still

tawny elkBOT
#
πŸ’‘ IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

β€’ Visual Studio (Installed via Unity Hub)
β€’ Visual Studio (Installed manually)

β€’ VS Code*
β€’ JetBrains Rider
β€’ Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

magic quiver
white iris
#

Ide the code editor

lean sail
#

your visual studio (its your IDE) needs to be configured to work with unity stuff

#

VS doesnt come with unity stuff right when u download it

magic quiver
#

how

lean sail
#

theres a big command right under my message

lean sail
white iris
magic quiver
#

ok

tepid geode
#

did anyone try to use com.unity.runtime-scene-serialization?
it looks really convenient for asset importers to create prefabs so I can create them in 3rd party dccs

the only thing I'm struggling is AssetPack in serialization metadata. it supposed to be lookup table for assets so it can stores ids which makes sense, but I have no idea how to actually create this table by myself.
seems simple but api is so cryptic

#

god we need proper usd support
all this NIH features are spreading like cancer

tender vault
#

do you guys have any good resources on a state machine?

craggy veldt
muted schooner
swift falcon
#

Hi , I have callbacks that come from an external source, and as I have read multiple times that unity is not thread safe, I use the "unitythread" class explained here: https://stackoverflow.com/questions/41330771/use-unity-api-from-another-thread-or-call-a-function-in-the-main-thread My question is if this is a correct solution for handling with this type of callbacks or there is a better solution (as the answer is from 2018)

craggy veldt
#

you'd need to do your own dispatching

#

or just the simplest way by queueing your thread into monoBehavior

#

wrap it in a delegate and you can use ConcurrentQueue to queue all those calls and have it run on Update

void Update()
{
  while(myConCurrentCue.Count > 0)
  {
      //dequeue and invoke from MonoB
  }
}
#

just a simple and ugly example, but you shoould get the idea

swift falcon
#

so the "UnityThread" script from the stackoverflow answer is too complicated for the thing I do? Because it works, its just that I dont know if its the best solution for this.

craggy veldt
#

if it works, then it works πŸ˜„

thin aurora
#

Unity is thread safe when you stick to Tasks, because the synchronizationContext in Unity is redefined to run everything in a safe thread that won't throw exceptions because Unity methods can't run on seperate threads.

#

The only reason to dispatch it back to the real main thread is to avoid race conditions, but you also have concurrency tools for this

craggy veldt
thin aurora
#

There's no need to manually invoke something from the Task factory

#

Unity works fine when you declare an async-Task method, so you don't need to create a whole invokation machine to fix something that isn't broken, unless you manually create threads or use the Task factory

#

Honestly I'm surprised Task.Run doesn't run either

swift falcon
#

Its a callback that returns some coordenates from an eye tracker, like 30 times per second. I tried using events but I dont know why after some seconds sometimes it just stops working. Then I thought it may have something to do with threads, and I tried this "unityhread" thing from stack overflow and it works. Maybe the error comes from another source I dont konw hahaha I just wanted to know if there is a better method at handling different threads. Im just learning so there are a lot of things I dont understand πŸ˜… I dont event know if that is an async method or not

thin aurora
#

So that's weird

#

Anyway, that unityThread is also nice. It basically saves delegates (so anonymous "methods"), and invokes them in an Update method, which guarantees to run on a supported thread. I see it also supports Coroutines. You can totally use it

#

I don't know how threaded that eye tracker is, but I would assume they atleast account for proper threading.

swift falcon
#

ok, thanks, I will just stick to that then πŸ˜„

azure heath
#

Hey, I'm trying to crop a sprite at runtime through a script. I've figured out that I can do it using Sprite.Create() but it's a bit awkward. Is there any other way to do this? Also, I want the sprite to animate but when I do this it stops animating, so is there anyway I can crop every frame of an animation?

steady moat
swift falcon
#

Hey, I'm trying to understand (using the old unity input system) if the player is using (or has used) the keyboard or the gamepad. any suggestions please?

swift falcon
# steady moat Input.GetKeyDown(); ?

no like i want to detect if the last button pressed was on keyboard/mouse or on a controller, so that i can know wether the player is using a gamepad or a pc

steady moat
leaden ice
swift falcon
steady moat
swift falcon
#

idk what old input system you are talking about

leaden ice
#

The Input class

swift falcon
#

i mean the one that uses Input.GetKeyDown for example

steady moat
#

using the old unity input system

swift falcon
leaden ice
#

Yes that's the old system

swift falcon
steady moat
#

This cannot easily indentify controller.

leaden ice
#

And it will be very hard to do what you want with it

#

Recommendation is to switch to the new system

steady moat
#

You could, make 2 key bind for each binding.

leaden ice
#

Which can do this pretty easily

steady moat
#

One without the gamepad and one with only the gamepad.

swift falcon
steady moat
#

However, that would be kinda stupid.

swift falcon
swift falcon
steady moat
#

However, the real solution is to upgrade to the new input system.

swift falcon
#

i have tens of actions

swift falcon
steady moat
#

Yeah, exactly. I'm not saying it is a good solution.

steady moat
#

I use Rewired, so I cannot help you.

swift falcon
#

okk thanks

#

if anyone else can help please

stone knot
#

hi guys, any know what i need to use a websocket client in unity to connect to our server, what is the best option for work in pc, consoles and mobile?=

leaden ice
heady iris
#

I know there's some code floating around in the package

leaden ice
#

Yes it's in the docs

blissful nacelle
#

Hi, I've been trying to build a project which has nothing really special, but for some reason launching the build (no error), starts the process but doesn't open any window (the process also never closes so I have to close it through the Task Manager).
It happens on multiple machines, works if I do the same with a fully empty project.
The log output is basically empty. Using Unity 2022.3.2. Any idea please ? : D

worn oasis
#

Hello everyone, I'm running into an issue where the mouse sensitivity is different in the editor from the build. Increasing the sensitivity does not fix the issue (build-side) and I doubt it has anything to do with my code. Any input on this? Would really appreciate the feedback.

leaden ice
#

(i.e. it's your code)

worn oasis
leaden ice
#

yes

#

that is an error

#

remove it

#

(and reduce sensitivity to compensate)

worn oasis
#

Okay, giving it a go

worn oasis
# leaden ice remove it

Hmm, now it's super choppy, full code for reference:

void Update()
    {
        //if (!IsOwner) return;

        float mouseY = Input.GetAxis("Mouse Y") * sensitivity;
        float mouseX = Input.GetAxis("Mouse X") * sensitivity;

        xRotation -= mouseY;
        yRotation += mouseX; 

        //Debug.Log(1/Time.deltaTime);

        Debug.LogFormat($"<color=green>MouseY: {mouseY} - MouseX: {mouseX} - xRotation: {xRotation} - yRotation: {yRotation}</color>");

        xRotation = Mathf.Clamp(xRotation, -90f, 25f);

        //This works properly now:
        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);

    
        
        if (player != null)
        {   
            player.Rotate(Vector3.up * mouseX);
            //transform.position = player.position + offset; // Set the camera's position to match the target's position plus the offset

        }
        
    } ```
leaden ice
#

shouldn't be choppy - did you reduce sensitivity?

worn oasis
#

yes

leaden ice
#

what is it set to

worn oasis
#

0.0001f

leaden ice
#

should be around 1ish

leaden ice
worn oasis
#

too fast

quartz folio
#

Are you sure you saved?

worn oasis
#

yes

#

public float sensitivity = 0.000000001f; // Mouse sensitivity

still super fast

leaden ice
#

change in the inspector

worn oasis
#

I can't. The issue is in the build not the editor

leaden ice
worn oasis
#

'Build and Run'

leaden ice
#

no

#

go to the inspector for your player object

#

change the sensitivity value there

#

that value goes into the build as well

worn oasis
#

Ohh, yea that, the player look is a singleton o.O

leaden ice
#

irrelevant?

worn oasis
#

okay

quartz folio
#

The value of serialised variables is set via the inspector, the value set in code is only the initial default and changing it once set does nothing

worn oasis
#

@leaden ice @quartz folio It baffles me as to how you guys knew that I had the sensitivity variable as public/ serialized

#

Making it private fixed the issue

#

I'm very grateful for you guys. Really appreciate the help

#

FYI, you can't change variable values of singletons in the editor.

leaden ice
worn oasis
#

or at least I can't

worn oasis
leaden ice
#

you find the object with the script on it

#

and you change the value in its inspector

#

it exists somewhere in your project

#

either in a scene or as a prefab

worn oasis
#

Yes, but the singleton isn't attached to the object, the parent script just references it

leaden ice
#

they cannot exist without being attached to a GameObject

worn oasis
leaden ice
#

this script is attached to a GameObject in your scene somewhere

worn oasis
#

But it doesn't inherit from Monobehavior

leaden ice
#

yes it does

worn oasis
#

Let me check

leaden ice
#

because Singleton does

worn oasis
#

Oh

leaden ice
worn oasis
#

Oh right πŸ˜…

worn oasis
#

Thanks again!

heady iris
blissful nacelle
#

Though there is no compilation or launch error, nor warning, just nothing

heady iris
#

"though" made it sound like you were talking about the empty project

blissful nacelle
#

Sorry, yes, I mean no error in our project

scarlet hill
#

so, I'm getting some issues with ViewportToWorldPoint.. Magenta lines are what it detects in code (moves and scales relatively with the camera position)

private Rect GetScreenWorldRect(Camera value)
    {
        Vector3 bottomLeft = value.ViewportToWorldPoint(new Vector3(0f, 0f, 0f));
        Vector3 topRight = value.ViewportToWorldPoint(new Vector3(1f, 1f, 0f));
        return (new Rect(bottomLeft.x, bottomLeft.y, topRight.x * 2f, topRight.y * 2f));
    }

        Debug.DrawLine(new Vector3(sqr.xMin, sqr.yMin, 0f), new Vector3(sqr.xMax, sqr.yMin, 0f), Color.magenta);
        Debug.DrawLine(new Vector3(sqr.xMin, sqr.yMax, 0f), new Vector3(sqr.xMax, sqr.yMax, 0f), Color.magenta);
        Debug.DrawLine(new Vector3(sqr.xMin, sqr.yMin, 0f), new Vector3(sqr.xMin, sqr.yMax, 0f), Color.magenta);
        Debug.DrawLine(new Vector3(sqr.xMax, sqr.yMin, 0f), new Vector3(sqr.xMax, sqr.yMax, 0f), Color.magenta);
#

any ideas?

heady iris
#

i don't understand the problem

leaden ice
scarlet hill
#

magenta lines are the exact thing code outputs

#

and the white lines are the camera itself

leaden ice
#

It's not really clear to me that they are not aligned, as the screenshot is a little unclear

#

Are you sure you're passing the correct camera in?

scarlet hill
leaden ice
scarlet hill
#
public class windVFX : MonoBehaviour
{
    private Rect sqr;

    [SerializeField]
    private GameObject particles;
    [SerializeField]
    private GameObject player;
    [SerializeField]
    private Camera cam;

    private PlayerController controller;

    [SerializeField]
    private float timerMax = 0.4f;
    private float timer;

    void Awake()
    {
        controller = player.GetComponent<PlayerController>();
        sqr = GetScreenWorldRect(cam);
    }

    private Rect GetScreenWorldRect(Camera value)
    {
        float height = value.orthographicSize * 2;
        float width = height * value.GetComponent<CameraScale>()._targetAspectRatio;
        Vector3 bottomLeft = value.ViewportToWorldPoint(new Vector3(0f, 0f, 0f));
        Vector3 topRight = value.ViewportToWorldPoint(new Vector3(1f, 1f, 0f));
        Debug.Log($"Position : {transform.position} Local : {transform.localPosition} Camera Pos : {cam.transform.position} Camera LocalPos : {cam.transform.localPosition} Width : {width} Height : {height}");
        return (new Rect(bottomLeft.x, bottomLeft.y, topRight.x, topRight.y));
    }

    void Update()
    {
        //Debug.Log("Rect xmin: " + sqr.xMin + " xmax: " + sqr.xMax + " ymin: " + sqr.yMin + " ymax: " + sqr.yMax);
        Debug.DrawLine(new Vector3(sqr.xMin, sqr.yMin, 0f), new Vector3(sqr.xMax, sqr.yMin, 0f), Color.magenta);
        Debug.DrawLine(new Vector3(sqr.xMin, sqr.yMax, 0f), new Vector3(sqr.xMax, sqr.yMax, 0f), Color.magenta);
        Debug.DrawLine(new Vector3(sqr.xMin, sqr.yMin, 0f), new Vector3(sqr.xMin, sqr.yMax, 0f), Color.magenta);
        Debug.DrawLine(new Vector3(sqr.xMax, sqr.yMin, 0f), new Vector3(sqr.xMax, sqr.yMax, 0f), Color.magenta);
    }
scarlet hill
swift falcon
#

Is there a way to get interface variables to show up in the inspector for ScriptableObjects?

#

how do i make my rigid body walk on a sphere from the inside (and rotate to make its legs always face the walls)... it's been driving me nuts

leaden ice
swift falcon
#

@steady moat @leaden ice Thank you and I'll give it a read

vernal plank
#

quick question why is cube.transform.position

#

not accepting Vector3 box_location = new Vector3(0,3.38,0);
Argument 2: cannot convert from 'double' to 'float'

heady iris
#

sounds fine. show the assignment.

#

perhaps you are attempting to do this outside of a method

knotty sun
#

because 3.38 is not a float value

heady iris
#

ah, yes, that will slow you down.

vernal plank
heady iris
#

because it is a double

knotty sun
#

it's a double

#

like the message tells you

heady iris
#

which you should be reading

vernal plank
#

okay doky

heady iris
#

rather than just seeing an error and stopping

vernal plank
#

but i want the cube to be at 0 , 3.38 , 0

#

how can i achieve that then

knotty sun
#

then learn how to write float constants

vernal plank
#

sorry

heady iris
#

then you need to learn to write C#, yes

#

you will be writing a lot of float literals

#

(a "literal" being anything that literally has a value)

#

"hello", 123, 40.0f, ...

marsh wadi
#

The docs for BuildPipeline.BuildPlayer mention a problem with domain reloading

... the built-in scripting symbols defined for the current active target platform (such as UNITY_STANDALONE_WIN, or UNITY_ANDROID) remain in place even if you try to build for a different target platform, which can result in the wrong code being compiled into your build.

if i understand correctly, this means that if i try to build a dedicated linux server build via code, it won't have the correct defines set

is there a way around this or do i just need to switch the build platform every time?

knotty sun
#

you can write your own build script

vernal plank
#

is C# and extention of C or just inspired by it ?

sleek bough
marsh wadi
swift falcon
stark jacinth
#

!code

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

stark jacinth
#

my player health code: https://gdl.space/eyikiduvof.cs
my AI enemy code(shorter version): https://gdl.space/rehahejibe.cpp

on my AI enemy code I'm getting an error on line 40: Object reference not set to an instance of an object

I searched up this error and unity is saying that the component in my game on that line of code doesn't exist, but it in fact does.So, I was wondering If anyone could see what I'm doing wrong.

knotty sun
#

playerhealth is null, did you set a value in the inspector?

stark jacinth
#

Yes, I've set it to 100

knotty sun
#

no, playerhealth is a class not an int

stark jacinth
#

my reference to my script is playerHealth and inside that script playerHealth is a public float

knotty sun
#

but your reference is null

stark jacinth
#

oh shit, I'm an idiot

#

i should put it to private

#

i dont know why I did public

knotty sun
#

it will still be null unless playerhealth is on the same game object

stark jacinth
#

oh yea, so I would set it to the object that holds my playerHealth script

#

correct?

knotty sun
#

yes, leave playerhealh public, fill it in the inspector and remove the getcomponent from your script

stark jacinth
#

I still get the same error

#

is it because my player holder is an empty transform

#

does that matter?

knotty sun
#

show latest code and screenshot inspector for gameobject with BananaBoy

stark jacinth
#

it has to be a gameobject thats my mistake

stark jacinth
knotty sun
#

you did not remove the GetComponent like I said

stark jacinth
#

ok it works

#

I dont need GetComponent because their not on the same object

#

sorry ab that

knotty sun
#

no, you dont need GetComponent if the reference is filled in the Inspector

#

in this case you are overriding the inspector reference with null

stark jacinth
#

yea, but for my other scripts I never referenced it in the inspector and just used GetComponent because their on the same object.

#

is that not why it worked with my other scripts?

knotty sun
#

yes, it is

stark jacinth
#

yea just wanted to make sure

#

thanks tho

shut ridge
#

Hello!
I've been trying to add a rotating rigidbody (with the ability to move) as a sort of joint for another rigidbody, with a script that rotates said joint, but for some reason, the joint also moves with its arm

#

why is this?

#

the script is only set to rotate the joint, not let it omve

sleek bough
shut ridge
#

i do

#

im using a distancejoint2d

#

and the joint is attached to a hinge joint 2d on a parent

sleek bough
#

If you don't want for forces to propagate to another rigidbody, set limitations.

shut ridge
#

how would one do this?

#

i'm very new to joitns

#

*joints

#

can't even spell lol

#

wait
ok

#

good news: I got it working

#

bad news: The joints don't move with moveposition();

sleek bough
shut ridge
#

would that assist with moveposition

#

*?

sleek bough
#

Move position is not a physics method to move things. It just updates rigidibody position

ashen hull
#

Guys, I heard that we could make camera shaking with coding C#. Not game playing camera shake. I meant its normal shaking like you have watched some short film that when FPS walking, idle-ing, etc. like camera shaking in cinematic film

#

Or I want the code from github

#

or is there any tutorial of it

shut ridge
#

ok then
well
ig i'll just move the rest of the rigidbodies with it

#

or wait

shut ridge
ashen hull
#

oh really?

#

ok then

sleek bough
vernal plank
#

it seem C# as hard as C++
is C# performance equivalent to C++ i read that its not

fervent furnace
#

c++ is the most difficult language (apart from those non-human readable language)
or the difficulty you are talking about is something like "writing a compiler in c# is difficult", "writing a browser in c# is difficult" ...

mellow hill
vernal plank
#

ohhhhhhhh i seeeee

#

is C# corss platform like you can devleop an app in C# and ship it to multiable OS like C++

mellow hill
#

C#/.NET along with Java is industry standard for large enterprise application such as banking/finance software

mellow hill
vernal plank
#

so if i wanna write a multi platform app i need .NET

shut ridge
vernal plank
#

well can .NET run on android ?

mellow hill
#

So I will say that you can write cross-platform, you can also leverage UI frameworks such as Avalonia (cross-platform WPF/XAML) and Xamarin for mobile applicatiopns

mellow hill
# vernal plank well can .NET run on android ?

Yes, Unity projects can be ported to Android/iOS and you have Xamarin that can be used for cross-platform development. There is also something called "Platform Uno" that allows you to share a single codebase across many platforms

craggy veldt
#

like, why?

#

Unity is already crossplat

mellow hill
#

You can also use ASP.NET applications and create web-based applications that will obviously be cross-platform as well

vernal plank
#

just trying to understand the eco system of each language

sleek bough
timber cloak
#

For my world Generation the chunks have some black edges around 2 of the sides.
I don't know what is causing it and it makes the chunks stick out too much. I know it is not shadows, the uvs and the lighting. I don't think it is the normals or the vertices but it might be.

wary coyote
# timber cloak

are you sure its not the lighting, because that is the exact appearance I would expect if all of the mesh' faces were part of a single smoothing group and that side of the mesh is not subject to directional light

#

Architecture(?) question - what is the most sensible and flexible way to write/manipulate a large array of Vec3 values? (And doesn't necessarily have to be Vec3 values if there's something smarter.)
XY Use case would be: picture any '3D graph mesh', the end goal I am seeking to support is ease of applying arbitrary transformations to the positions to the entire thing

#

thoughts that come to mind are a texture height map, or a greatly subdivided mesh, but I don't know how you'd then pass the arbitrary deformations into such a thing

#

Ideally it needs to support translation of XYZ coordinates per position, and if possible support being able to grab and scale any part of the array, or deform it. IRL example - support grabbing and manipulating a piece of cloth in a square-ish frame

timber cloak
wary coyote
#

Hm yeah no directional light there. I assume its also an unlit shader even though there's no light in the scene?

timber cloak
#

great observation. The material was lit. I changed it to an unlit now and then it works with light on so i think i will keep it like that

leaden ice
#

anyRectTransform.position
This isn't really enough information. First off - the coordinate space of the RectTransform changes depending on the Canvas' Render Mode.

Second - if it's NOT a world space point you are passing in, you will of course get a nonsense answer here

#

if I use the .position value of any RectTransform I should get its world position iirc
No. In Screen Space Overlay it will give you a completely separate coordinate space

#

Can you explain what you are trying to do here?

#

because that's how overlay works

#

it doesn't exist in the world

#

it's just overlaid on the screen

leaden ice
#

Sounds like you're just doing something wrong

#

I'd figure out what that is and fix that

#

rather than try to recreate this built in behavior yourself

fluid lily
#

Is there a way to tell if an asset reference changed in the editor between the last time the scene was open/when the scene is open?

#

Like if I renamed a prefab/scene and wanted to change serialized variables on my component.

covert scaffold
#

I want to make a randomized grid-based game. In my code i have generated a matrix of 1's and 0''s that represents the map i want. Would it be sensible to, at runtime, generate TileMap each time? It feels weird because when making the game it means i have 0 use for the unity visual UI, and as the camera pans around idk if it would slow down or if id need to make my own hack for "resetting" the grid and re-tecturing on the fly to make it look larger. It just feels like im doing it wrong

heady iris
#

since the GUID doesn't change

fluid lily
#

Ah perfect. I can just use the GUID then and not worry about the name.

#

I am assuming moving an asset outside of the editor could break the GUID though(not worried about this as that already is a bad practice).

heady iris
#

If you don't move the .meta file along with it, yes.

fluid lily
#

Wait, SceneManager has no way of getting scene by ID, is there a way to get the asset instance by ID durring runtime? I am assigning SceneAsset in editor(but that is editor only) so I am saving the data needed to get the scene info durring runtime from the SceneAsset.

craggy veldt
#

.scene is part of Unity asset

#

those api linked above will work

#

oh runtime... then that's another story

fluid lily
#

Indeed

craggy veldt
#

ideally you'd want to do this in edit-mode tho

fluid lily
#

So the workflow I have right now is. Add scene load component -> select the SceneAsset for the scene you want to load in editor -> this saves the data needed to load the scene during runtime. The problem is if I grab scene name in editor it wont update from a value change on the SceneAsset, if the scene name is changed it won't get updated in my script. So I am assuming I will use the links above to pull the info from the AssetDatabase at run time based off of the AssetID I get from The SceneAsset.

#

edited*

#

assuming AssetDatabase is not Editor only

craggy veldt
#

bad news for you

#

I mean, this whole thing can be made much simpler by accessing the indexer to change scene, no ?

fluid lily
#

what do you mean by indexer?

#

I am unfamiliar with this I think

#

Like the Scene build number?

craggy veldt
#

yes

#

tho that can go south pretty easily if you removed one of the scene then the buildIndex willl change too

fluid lily
#

I am assuming I would run into the same issue as using the name, if the order of scenes is changed, my in scene component's values won't be updated.

fluid lily
#

I am looking into adressables also, which seems to be the only way forward so far.

#

I mean I could also use scriptable objects, but πŸ˜‘

#

An asset to reference an asset is clumsy at best.

craggy veldt
#

I mean getting all scenes is as simple as πŸ˜…

        var scene = SceneManager.sceneCountInBuildSettings;
        string[] arr;
        arr = new string[scene];

        for (int i = 0; i < scene; i++)
        {
            arr *= Path.GetFileNameWithoutExtension(SceneUtility.GetScenePathByBuildIndex(i));*
        }
#

so you can do your own logic or a way to update your component or whatever

#

this is more like xy problem to me

fluid lily
#

Yeah getting scenes isn't the issue. I am trying to build a component that doesn't break on scene asset changes, while also not hardcoding the desired scene identification.

#

As using user input ID or name will break on changes, where an asset/addressable reference won't break on changes.

#

I mean not sure addressables will do what I want yet, as it is pretty expansive and I am still studying it

#

The unity hub, go to installs and then press instal editor. The newest for each release will be shown under the tabs. Also not a code question

#

Not sure, but also not the best place to be asking this.

#

Something under Graphics

#

For unity LTS is the newest long term support version, otherwie Alpha is the "newest"

simple egret
#

Take the latest LTS, it's the one that has the long term support (what LTS means). It's ordered by date, so the greater the date, the latest it is
Also not a code question so it doesn't belong in this channel

swift falcon
sudden lantern
#

Why am i getting this errors? I did something wrong? Its Netcode for GameObjects

leaden ice
sudden lantern
leaden ice
jaunty needle
#

How do I create a vector that is 45 degrees away from a point

leaden ice
#

Do your parameter types implement either of those mentioned interfaces or not?

leaden ice
#

A point is a position

#

To have an angle you need two directions

leaden ice
#

Basically you need more information than just a "point"

jaunty needle
#

Yes I know

heady iris
#

are you asking about a point on a plane?

jaunty needle
#

Wait I shall clarify further

#

These stairs spawn repeatedly following the up direction:

#
    {
        Vector3 spawnDirection = Vector3.up;

        for(int i = 0; i < maxStairsSpawned; i++)
        {
            Instantiate(stairPrefab, startPos.position + spawnDirection * i * padding, Quaternion.identity);

        }

    }

This is the script

jaunty needle
heady iris
#

so you want a vector that points up and forwards

#

you can just punch in whatever vector you want

#

Vector3.forward + Vector3.up, for example

#

An angle alone is not enough information. There are many vectors that are 45 degrees from the up-vector

jaunty needle
#

hmm

#

what if I wanted it to be variable

#

the steepness

leaden ice
#

the steepness is one thing

#

the other thing is which fricken direction do you want

#

if you want to say "both are variables" that's fine

#

it's enough to say there's a variable for that provided

heady iris
#

if you want the staircase to go forwards with a varying steepness, then the math is pretty simple

#

Quaternion.AngleAxis(angle, Vector3.right) * Vector3.forward

#

a positive angle might send that into the ground

#

i forget which way it rotates

jaunty needle
heady iris
#

i think rotations are counter-clockwise?

#

if not, then use Vector3.left or negate the angle

heady iris
jaunty needle
#

Omg! I found the code

#

Something like this

heady iris
#

ah, there you go: angle axis

#

although I don't understand why you're rotating around Vector3.forward

jaunty needle
#

I think he pointed that out

#

wait

heady iris
#

you probably want to rotate around the right vector in the local space of the staircase

jaunty needle
#

here

heady iris
#

using Vector3.right or Vector3.forward will make the behavior depend on which way you're facing

jaunty needle
#

Alright

royal pulsar
#

I'm making a 2D top down zombie game, I need some AI pathtracing for the zombie AI. I've tried using the A* Pathfinding Project and it works well but conflicts with my knockback system. Is it worth me writing my own A* pathfinding algorithm? I don't know how much work it would be.

heady iris
#

no, you just need to stop the A* system from updating positions while knockback is happening

#

or, you need to manually correct the position it's using

royal pulsar
#

just a simple bool toggle

#

that saves me a lot of work

heady iris
#

I haven't used the A* addon, but with the unity NavMesh system, you can directly set the agent's simulated position

#

I'm guessing something similar is possible

royal pulsar
#

that was my earlier approach, but the agent would teleport whereas my initial knockback implementation was gradual

#

i guess i could do it frame by frame but this method works fine now

heady iris
#

ye

#

you can just update the simulated position when turning the navigation back on

#

(it might already do that)

hexed oak
#

Is it appropriate to create a new instance inside the resource field of a using statement?

using (MyWriter writer1 = new MyWriter())
{
    writer1.Write(this);
}```
#

Traditionally it's not created through a new keyword, but from somewhere else like this

using (StreamReader numbersFile = File.OpenText("numbers.txt"), wordsFile = File.OpenText("words.txt"))
{
    // Process both files
}```
leaden ice
#

the only important thing is that the left hand side of the assignment is an IDisposable which you want to be disposed at the end of the scope.

hexed oak
#

Thank you

heady iris
#

there's no real difference between using a constructor and using a method

#

the method probably calls a constructor anyway

leaden ice
#

at some level every object created in C# has its constructor called

#

A static function like File.OpenText is just running the constructor on your behalf

#

It's totally legal to create the object earlier and use an existing reference in the using statement

#

There doesn't need to be an assignment

#

Example from C# docs:

StreamReader reader = File.OpenText(filePath);

using (reader)
{
    // Process file content
}```
#

also in newer C# versions you can just do:

using MyWriter writer1 = new MyWriter();
writer1.Write(this);
hexed oak
#

That's what I was thinking. Then the IDisposable dispose would destroy/cleanup things, but in this case the writer does not have any member variables

leaden ice
#

the fact of it having or not having member variables isn't really relevant

#

and that's not related to the presence of parameters in the constructor either

#

The things you might want to clean up aren't always member variables either

hexed oak
#

For Dispose wouldn't it be relevant so that you can call destructors on those managed member objects?

leaden ice
#

you don't ever need to call a destructor on a managed object

#

Unless you mean they are also IDisposables

#

and you mean to call Dispose)(

#

but no, the object could for example delegate to some other static reference to actually hold references to the things it needs to clean up

hexed oak
#

Yeah if the managed objects are also disposables

jaunty needle
#

Guys how do I use an animation curve to interpolate between a starting size and an end size
I want to create a pop up effect

leaden ice
#

If you have nothing to dispose there's no reason to be an IDisposable. But there's no limitation on what can be the disposable bits that need cleaning up

vernal plank
#

Well ill ask here after spending some time reading the api, In unreal we used to have a path for the texture (or the file) you wanna import
and a path inside the engine content folder, in unity only take one path AssetDatabase.ImportAsset

leaden ice
vernal plank
#

do i have to do a bash script that would throw files/textures inside of unity project folder

#

before improting them

jaunty needle
#

I want the animation to last x seconds

heady iris
#

count up

leaden ice
heady iris
leaden ice
#

0 being the start, 1 being the end

heady iris
#

it already does that

#

what are you trying to accomplish here?

hexed oak
# jaunty needle Guys how do I use an animation curve to interpolate between a starting size and ...

animation curve.Evaluate() method. Here's a sample that rotates over time, you'd want to use transform scale possibly instead

IEnumerator Lerp(float afEndValue)
    {
        float animationTime = 0;
        while (animationTime < _animationDuration)
        {
            _valueToLerp = Mathf.Lerp(_startValue, afEndValue, _animationCurve.Evaluate(animationTime / _animationDuration));
            transform.localRotation = Quaternion.RotateTowards(transform.localRotation, Quaternion.Euler(new Vector3(0, _valueToLerp, 0)), 179);
            animationTime += Time.deltaTime;
            yield return null;
        }
        _valueToLerp = afEndValue;
    }```
jaunty needle
#
    {
        Vector3 originalSize = gameObject.transform.localScale;
        gameObject.transform.localScale = Vector3.zero;
        float time = 0;

        while(true)
        {
            time = Mathf.MoveTowards(currentTime, timePopping, popUpSpeed * Time.deltaTime);
            gameObject.transform.localScale = Vector3.Lerp(Vector3.zero, originalSize, curve.Evaluate(time));
            yield return null;
        }
    

What's wrong with my code here

#

For some reason when I print time it keeps fluttering instead of just going to one

#

ohh

leaden ice
jaunty needle
#

No I'm starting in start

#

time = Mathf.MoveTowards(currentTime, timePopping, popUpSpeed * Time.deltaTime);

#

here

leaden ice
#

oh wait also your MoveTowrads is not using time as the first param

jaunty needle
#

yep

tepid brook
#

Hi guys i want to create a game with random event like RPG Game and i want some tips to make it easy like scriptable object or something like that someone can help me pls ?

pine haven
#

Quick question, but what the heck happened to the lighting? anyone can help me?

#

ignore the main menu

pine haven
#

i think lighting

#

wait this is the wrong channel

pine haven
pine haven
neat echo
#

could anyone help me figure out why my uvs might not be working correctly?

#

if theres a better channel to ask it in just lmk :]

heady iris
jaunty needle
#

yeah

neat echo
#

the texture is fine im pretty sure, im just struggling to get it mapped to the mesh correctly

heady iris
#

then ask your question and show your code.

neat echo
#

so basically i have a procedurally generated voxel mesh and just a little function that loops through every voxel and adds the uvs to it (based on a UV lookup table)

void AddUVs() {
  for (int i=0; i<24; i++)
    uvs.Add(uvLookup[i])
}

that code works and gets the uvs mapped nicely but in reality i need to give each face a different texture based on what face it's on, for each voxel i have a list of the visible faces (i.e. the faces that don't have another voxel right next to them), and i wrote this code to try and work with this new solution

#
    void AddUVs(List<Vector3> visibleFaces) {
    for (int i = 0; i < 6; i++) {
        if (visibleFaces.Contains(offsets[i]))
        {
            switch (i) {
                case 0: // y- face
                    uvs.Add(uvLookup[0]);
                    uvs.Add(uvLookup[1]);
                    uvs.Add(uvLookup[2]);
                    uvs.Add(uvLookup[3]);
                    break;
                case 1: // y+ face
                    uvs.Add(uvLookup[4]);
                    uvs.Add(uvLookup[5]);
                    uvs.Add(uvLookup[6]);
                    uvs.Add(uvLookup[7]);
                    break;
                case 2: // x- face
                    uvs.Add(uvLookup[8]);
                    uvs.Add(uvLookup[9]);
                    uvs.Add(uvLookup[10]);
                    uvs.Add(uvLookup[11]);
                    break;
                case 3: // x+ face
                    uvs.Add(uvLookup[12]);
                    uvs.Add(uvLookup[13]);
                    uvs.Add(uvLookup[14]);
                    uvs.Add(uvLookup[15]);
                    break;
                case 4: // z- face
                    uvs.Add(uvLookup[16]);
                    uvs.Add(uvLookup[17]);
                    uvs.Add(uvLookup[18]);
                    uvs.Add(uvLookup[19]);
                    break;
                case 5: // z+ face
                    uvs.Add(uvLookup[20]);
                    uvs.Add(uvLookup[21]);
                    uvs.Add(uvLookup[22]);
                    uvs.Add(uvLookup[23]);
                    break;
            }
        }

        else {
            for (int k = 0; k < 4; k++)
                uvs.Add(uvLookup[0]);   
        }
    }
}
#

the else clause at the end is because i need to have 24 uvs per voxel regardless

#

obviously after i get this working ill add in the code to actually work with each face independently but right now, this function should produce the exact same result as the old function but it isn't, can anyone help me figure out why?

#

been bothering me for the past few days sdfjkhsfdh

heady iris
#

in what way does the output differ?

neat echo
#

yee one sec i can grab a screenshot

#

this is the output from the first function

#

and this it the output from the second function

#

the first function also works with the breaking/placing blocks code, but when you try and break/place blocks in the second one, the blocks are removed/added correctly but the uvs get added incorrectly

#

like for example this

heady iris
#

are you sure that VisibleFaces isn't just wrong

#

you can throw in || true to make the if statement always run

neat echo
#

visibleFaces is used elsewhere in the code and works so i dont think so, but ill give it a shot

#

ah

#

interesting...

heady iris
#

Perhaps you have the order of the faces wrong in your new UV function, then.

#

That would explain why the top row showed up

neat echo
#

i might know what it is, ill try

neat echo
heady iris
#

i think you're correctly setting face visibility

heady iris
neat echo
heady iris
#

yes, because that skips the visible face check

#

so it always assigns the UVs

#

but it looks like every side of the object has the same texture on it right now, so you can't really tell...

heady iris
#

I think you have the switch cases out of order.

#

The visible faces are clearly right, since the cubes are rendering correctly.

neat echo
#

if i changed the order would it not just change the orientation of the faces

heady iris
#

well, clearly the order that you set the UV coordinates matters

#

your code says it's doing -Y, then +Y, then -X, ...

#

I think your order is wrong.

#

I'm not talking about the order within each case

#

I'm talking about the order of the cases.

neat echo
#

ah right i get you now

#

how do i know which order they should be in?

heady iris
#

i dunno how your mesh is laid out

#

the order of the quads will matter

neat echo
#

everything is in the same order im pretty sure except for the offsets

#

im not sure why but when i put the offsets in the same order as everything else

neat echo
fluid lily
#

Is there a way to load a scene by GUID? I was looking into Addressables, but how they are resolving the GUID to asset is hidden behind AddressablesImpl.LoadSceneAsync and haven't been able to look at the source.

neon plank
#

Does RuntimeHelpers.RunClassConstructor works in AOT platforms?

serene musk
#

Hello, I have a small problem.
First, a bit of context.
It's about object pooling for bullets and how to handle them effectively.

I have a "Bullet" script that essentially tells the bullet to return to the pool when it goes outside the camera's field of view.

Since it's a shoot 'em up game, I have some doubts about this system.
Would it be more sensible for the camera to take over the object pooling? By saying that when a bullet leaves the camera's view, throw it back into the pool.

#

But on the other side im more flexible with the bullet script since i can extend the pooling conditions for each bullet ..

heady iris
#

the bullet can check if the camera can see it

serene musk
#

yea thats the way i have it now

compact spire
#

Can I generate sprites from spritesheets at runtime without using the UnityEditor namespace, or is that still a required thing?

#

nevermind, that was suprisingly easy to look up

digital hemlock
#

help raycasting ui object

leaden ice
digital hemlock
#

this is what ive got so far but it doesnt detect anything

#
            Vector2 screenCenter = new Vector2(Screen.width / 2f, Screen.height / 2f);

            // Perform a raycast from the center of the camera
            Ray ray = mainCamera.ScreenPointToRay(screenCenter);
            RaycastHit hit;
            Debug.DrawRay(ray.origin, ray.direction * 100f, Color.red, 1f);
            if (Physics.Raycast(ray, out hit, Mathf.Infinity))
            {
                // Check if the hit object is on a UI canvas
              
                    // UI object is hit, do something
                Debug.Log("here3 ");

            }

            Debug.Log("here2 ");```
leaden ice
#

UI elements don't have colliders

#

Physics.Raycast only works on colliders

#

do noy use Physics.Raycast

#

use the event system

digital hemlock
#

how do you do that

leaden ice
#

depends what you want to do

digital hemlock
#

i just want to get the gamobject over the centre of the screen

leaden ice
#

Is your cursor locked? It's unclear why a UI element would be in the center of the screen

#

and why you wouldn't know if it is

#

what kind of game is this

digital hemlock
#

i am moving the ui objects around

#

its an osu aim trainer

leaden ice
#

so you actually want to know if the pointer is over a UI element

digital hemlock
#

not the pointer

#

centre of the screen

leaden ice
#

you really shouldn't use UI for an OSU trainer

#

use 2D sprites

#

you're making a classic mistake

#

don't make your game out of UI

#

UI is not for gameplay

digital hemlock
#

ok

#

its just test phasing right now

#

can you not mess with my head

leaden ice
#

and use Physics2D.GetRayIntersection to detect 2D colliders from a screen ray

digital hemlock
#

thank you

hard tapir
leaden ice
#

yes

#

SpriteRenderer and Collider2Ds

covert scaffold
#

I have an array called LevelData.entities and i wish to store a reference to Player which is an entity stored in that array. Do i use a pointer here? Im worried that i make a reference to the player-object in the array then when i clear out the array it wont delete the Player since they still have a reference

digital hemlock
#

so this doesnt work for ui

#

so something as simple

#

as raycasting the ui

leaden ice
digital hemlock
#

is not possible

covert scaffold
leaden ice
hard tapir
leaden ice
digital hemlock
#

please dont backseat drive my game i have autism and dont like talking about it cause i get embarassed so i just made up a game ideaa

hard tapir
#

You use mouse for buttons or sliders

heady iris
digital hemlock
#

i just need to raycast the centre of the ui

leaden ice
digital hemlock
#

please the advice was. hopw do i raycast the ui

#

you said

covert scaffold
digital hemlock
#

WHATS YOUR GAME

#

WHAT IDEA IS IT

#

NO BAD

#

GRUNTS

leaden ice
# digital hemlock NO BAD

If you want someone to fix your car, you should probably tell them what kind of car it is and what's wrong with it. It's not my problem if you can't handle simple clarifying questions.

heady iris
digital hemlock
#

bro RAYCAST UI

#

RAY. CAST. UI.

leaden ice
#

Bye

heady iris
#

i.e. why do you need that reference and to have the player in the array?

hard tapir
covert scaffold
# digital hemlock WHATS YOUR GAME

if you dont know how to do it then ur probably also unaware of the better solutions. If i asked how to launch a thread to query a website i probably dont know that you can use a coroutine

leaden ice
digital hemlock
#

please please please i just want to know how to raycast ui

#

yall dont understand im trying to prototype in the easiest convenience

#

ive never used unity 2d before

#

but i understand the ui system

covert scaffold
digital hemlock
#

thanks for wasting my time like yall waste your time using an outdated game engine

covert scaffold
heady iris
heady iris
#

perhaps we can help you then

digital hemlock
#

i dont have 4 i only have 3 . 5 which is trash

hexed oak
digital hemlock
#

bruh stingy comments = bad

digital hemlock
#

one comment slightly stingy = BADDDD

#

ok i concede defeat

#

i will build it in 2d

#

ok ok

covert scaffold
#

OH WAIT nvm their position wouldnt change so no need

hard tapir
#

@digital hemlock

sleek bough
#

@hard tapir No need to rehash this

hard tapir
#
{
    PointerEventData eventData = new PointerEventData(EventSystem.current);
    eventData.position = new Vector2(Screen.width / 2f, Screen.height / 2f);
    List<RaycastResult> results = new List<RaycastResult>();
    GetComponent<GraphicRaycaster>().Raycast(eventData, results);

    foreach (RaycastResult result in results)
    {
        Debug.Log("Hit UI element: " + result.gameObject.name);
    }
}
digital hemlock
#

godot because its free and under mit liscence, and unreal because it has better tech

hard tapir
digital hemlock
#

i answered ur question see

#

im part of the community

hard tapir
sleek bough
#

@digital hemlock There's no off-topic here. Enough with this already.

heady iris
#

yes, there is a GraphicRaycaster

digital hemlock
#

sorry

heady iris
#

I was rooting around for the documentation

#

it only targets graphic elements

sleek bough
#

@hard tapir Stop with provocations

hard tapir
#

Actually to be honest, it's not about engine but it's about you

#

All engines has their cons and pros

digital hemlock
#

does this work with ui @hard tapir ?

heady iris
#

that is the point of the GraphicRaycaster, yes

#

The engine uses it to decide what you're clicking on

digital hemlock
#

my scene consists of an event system. a canvas and a camera

#

and a raw image

hard tapir
digital hemlock
#

i have the raycasting function running in the update

#

do you need to put the script on the camera?

hard tapir
digital hemlock
#

i get an error on this line GetComponent<GraphicRaycaster>().Raycast(eventData, results);

#

NullReferenceException: Object reference not set to an instance of an object

sleek bough
hard tapir
#

Go into canvas, then add gtaphic raycaster component

digital hemlock
#

ok sweet

last idol
hard tapir
digital hemlock
#

public GraphicRaycaster rc;

hard tapir
#

Yes

simple egret
#

No!

hard tapir
#

Or serialize field private

simple egret
#

The code already searches for a GraphicRaycaster

#

You don't need a field

digital hemlock
#

YES IT WORKS

#

THANK YOU MY KIND KING

#

YOU ARE A REGAL RULER

hard tapir
hard tapir
simple egret
#

My point was that, because the code used GetComponent<>(), no need to create a field and drag-drop

hard tapir
simple egret
#

Yeah but the script you provided, and you probably didn't read is meant to be on the same object as the Event System and the Graphic Raycaster

hard tapir
#

But if it's attached on that canvas with graphic raycaster then indeed, toi don't need to

hard tapir
simple egret
#

Yes

dapper mural
#

Hey there guys, is it there any way to modify/reimport a mesh/asset after building the project?

leaden ice
#

Modify the asset, reimport, rebuild the game

neat echo
formal wyvern
#

I want to create a new instance of a material for a bunch of instantiated objects at startup, but then update properties in those materials Update() without creating new objects

#

doing myObject.GetComponent<MeshRenderer>().material.SetFloat(...); does indeed seem to make a copy (which is good, since I can't call new Material() in udon, and this is a VRChat world)

#

if I just keep a reference to myObject.GetComponent<MeshRenderer>().material and call SetFloat() on it later, would that update without a new copy? I don't see why it would be any different...

wind stream
mental rover
#

don't think of it as "locking the cursor to a radius"

heady iris
#

yeah, that would probably annoy the user

#

and you don't want to annoy me

#

i complain very loudly

rugged storm
#

whats the best way to basically just render a 2d array of colors to the screen
i want to make a game similar to Niota and I'm trying to render the elements to the screen

leaden ice
#

You can then modify the texture either with a compute shader or just in C# code

waxen crest
#

Anyone know why my raycast works in the editor but not in a built instance?

blissful yoke
#

What is the idea behind Gui Cameras?

leaden ice
waxen crest
# leaden ice Not without seeing your code etc.
    {
        if (Input.GetMouseButtonUp(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit, 9999.0f))
            {
                if (hit.transform.gameObject.GetComponent<Hero>())
                {

                    Hero hero = hit.transform.gameObject.GetComponent<Hero>();
                    uiHandler.EnterMovementMode();
                    uiHandler.selectedUnit = hit.transform.gameObject;
                   
                }
                else
                {
                    image.SetActive(true);
                    return;
                }
            }
        }
    }```
#

the image.SetActive(true) is just for debugging in steam

leaden ice
#

You can just use Debug.Log

waxen crest
#

how do u access logs from a steam instance?

leaden ice
#

It will write to the player log

#

As long as it's a dev build

waxen crest
#

thanks

#

any idea why the ray would only cast in the editor and not a built instance?

leaden ice
#

It won't

#

Your issue is probably due to script execution order issues or framerate differences or something along those lines

#

You need to add logs and question your assumptions

#

E.g. make sure the code is running as expected and there's no errors etc

waxen crest
#

alright thanks

blissful yoke
#

Can anyone here recommend a course on best practices in coding GUI?

#

I have not much idea in how to tackle that. I know how to do basic ui stuff, but not really an idea of how to do it well.

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

void basalt
silver ferry
#

does AssetDatabase.RemoveObjectFromAsset automatically call AssetDatabase.DeleteAsset? or will not deleting them cause a leak

rain minnow
silver ferry
#

oh i see

#

i was having some trouble calling deleteasset myself

#

so i just called saveassets ye @rain minnow

rain minnow
#

yep . . .

sage pike
#

hi,
how can i distinguish between click events from UI TOOLKIT Element and click event when the user only click within the screen area?
when the user click button ui element i receive click events from both ui element and screen click.however, i receive one click event when the user is click within the screen area only.
I'm using unity new input system and ui toolkit.
help please

swift falcon
#

Is there any sort of different preferred naming system for async tasks akin to coroutines?

IEnumerator C_ExampleCoroutine() { ... }

async Task ExampleTask() { ... }```
#

ChatGPT is giving me this? What do ye think?

async Task ExampleTaskAsync() { ... }```
twin hull
#

@swift falcon ask whoever is going to read it in future

swift falcon
#

Just me then I guess. Has anyone else seen appending -Async before or did the AI make that up though?

#

I'm very new to multithreading btw

twin hull
#

if you're solo you can just do whatever. i don't name my coroutines like that and i never had any problems πŸ€·β€β™‚οΈ

simple egret
#

It's some convention for methods marked as async, postfix them with Async, so they can be differentiated from sync methods

grave hazel
#

anyone have a solution?
when I click the play button it goes straight out of the editor. from yesterday it was safe, there were no problems until noon. then when it was a bit late this afternoon it appeared on all the projects

simple egret
grave hazel
#

thanks, i will try it

heady iris
#

The third and fourth errors are both from a network problem

pure scarab
heady iris
#

are you hitting enter twice or something?

pure scarab
#

nope

heady iris
#

ah right, you clicked Delete

#

That's a new one. Did you already follow the instructions to set up the !ide ?

tawny elkBOT
#
πŸ’‘ IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

β€’ Visual Studio (Installed via Unity Hub)
β€’ Visual Studio (Installed manually)

β€’ VS Code*
β€’ JetBrains Rider
β€’ Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

pure scarab
#

yeah, i've done this

heady iris
#

okay, so it's not like unity has some kind of default "annoy user" mode if you haven't configured this

#

i wonder if this is VS's fault

#

what happens if you delete a file (and its .meta file) without Unity being focused?

pure scarab
#

let's see

heady iris
#

If that doesn't make anything happen, then it must Unity doing it

#

but I have no idea what would cause that

pure scarab
#

okay so i deleted the file and nothing happened, then i focused back to unity and it started loading and then visual studio opened

#

(deleted the file in file explorer)

heady iris
#

can you show me the External Tools settings?

#

i wonder if the command is messed up

#

but that only runs when you actually ask it to open a file..

pure scarab
heady iris
#

what version of unity is this?

pure scarab
#

2022.2.17

heady iris
#

ah, nevermind; this only appears when using the Code editor

#

my only thought would be to try unchecking everything and seeing if the behavior changes at all

#

it doesn't make sense, but...

pure scarab
#

still doesn't work

#

hmm

heady iris
errant shore
#

Can someone help me ?

#

on the subject of code

wide dock
steady moat
#

Ask your question.

errant shore
heady iris
#

do not cross-post, especially when you're just asking people to give you code

errant shore
#

WTF WHERE IS IT?

quartz folio
wide dock
errant shore
steady moat
#

What was not working ?

wide dock
steady moat
#

Did you have compilation error ?

errant shore
#

its not working, i dont know why

wide dock
#

Well then, what's your error?

leaden ice
#

Why are you doing position+forward as the starting point?

errant shore
errant shore
leaden ice
#

Are you expecting it to fire... abnormally?

errant shore
leaden ice
#

What does shoot at range mean

errant shore
fathom shore
#

First within the method

errant shore
leaden ice
#

You need to clearly explain what you are expecting to happen and what is actually happening

#

I suspect there's a language barrier issue here too unfortunately because from my perspective you're just kinda saying random stream of consciousness statements.

quartz folio
errant shore
errant shore
fathom shore
#

What’s the bulletspeed

quartz folio
errant shore
wide dock
quartz folio
#

Stop.

errant shore
quartz folio
cold egret
#

- Is there a way to calculate font size for tmp so that it vertically fits in N world space units (NOT canvas space)?

muted schooner
#

Do you guys know how effective is a Singleton in unity? Should I use them or does it hit the performance hardly in the later periods?

#

specially in single player games, enemies has to reach the player object, which may be done by checking nearby objects or directly using a singleton

#

I don't want them to check the nearby objects and spend effort in that way

#

but not sure if singleton worths it

#

or as a third option I have to send a reference to enemy spawner and give the reference to the enemy

#

which sounds better than the two

heady iris
#

singletons are not a performance concern

#

they do, however, add a design constraint: they're a singleton!

#

making something a singleton that should not be a singleton can create headaches down the line

#

imagine you have an inventory system, and you decide to make that a singleton, because only the player has an inventory

#

but then, later, you realize enemies should also have an inventory

#

now you have to fix everything that depends on being able to easily find that singleton

warm stratus
#

Hey, i am getting a text from a textAsset with textAsset.text but when i try textAsset.text.Split("\n\n") it doesn t work but i have (image) in my text file

swift falcon
#

i want to detect if a game object or more are on a specific direction, but i want to detect them even if they're within a +5 or -5 degrees range from that direction... how do i do that

knotty sun
warm stratus
quartz folio
#

\r\n, if you can remember CRLF that might help

warm stratus
#

i put \n\r and it worked

quartz folio
#

Presumably that is because you have two in a row and removed the middle bit (\r\n\r\n => \r\n), which is a bad way of going about things

warm stratus
quartz folio
#

You should remove the CRLF (\r\n) series of characters, not \n\r, which isn't a thing, it just happens to do produce the same outcome.

gray mural
#
string[] lines = operationtext.Split(new[] { Environment.NewLine },  
                                     StringSplitOptions.RemoveEmptyEntries);
warm stratus
#

my problem is just for the textFile

gray mural
gray mural
#

this method splits text file into lines

warm stratus
#

beceause it works

gray mural
warm stratus
gray mural
#

\r\n for non-Unix platforms, or \n for Unix platforms

heady iris
#

some systems encode newlines as a carriage return and a newline. others do just a newline.

#

I guess the bigger question is: where is this text coming from?

gray mural
heady iris
#

because that determines how the newlines will be encoded

gray mural
heady iris
#

note that you can probably just split on \n and then strip the resulting strings

warm stratus
heady iris
#

I wonder if that means the newline encoding will depend on platform (if you, say, use Git to version-control this)

gray mural
#

so Environment.NewLine is a better solution

heady iris
#

That's what I would reach for, yes.

heady iris
warm stratus
#

that s horrible, i need a different code for every platform???

quartz folio
heady iris
#

check this out

#

I didn't even KNOW about some of these newline sequences

gray mural
warm stratus
gray mural
#

\r escapes sequence within strings

heady iris
#

It does sound ike you could just slap the string with that method and then split it normally

heady iris
quartz folio
#

newlines are easy, just wait until you have to localise something

heady iris
#

You see, once upon a time, we used teletypewriters instead of screens

gray mural
#
string message = "Hello\rWorld";
Console.WriteLine(message);

// output: World
heady iris
#

Literally just a typewriter controlled by a computer

#

CR would reset the carriage to the start. It's a horizontal reset.

#

\n is LF -- line feed. That would advance the paper.

#

So, to properly reset for a new line of text, you had to send a CR and a LF

#

Linux-y operating systems discarded this and just use a LF character.

#

Windows did not (thanks Steve!)

#

wait, that's Apple

#

thanks Bill!

heady iris
swift falcon
#

guys I have been trying to detect if a game object is within 10 degrees from a direction... should i do multiple raycasts or what ?

heady iris
#

by default, it uses Environment.NewLine

warm stratus
#

and for Android?

heady iris
heady iris
#
Vector3 toObject;
Vector3 forward;
float angle = Vector3.Angle(toObject, forward);
#

(obviously, those two variables must have values put in them)

warm stratus
#

i know i can maybe just modify that and use always \n\r

swift falcon
heady iris
quartz folio
heady iris
#

get a vector to the object. get a vector in the direction of interest. compute the angle between them.

heady iris
gray mural
swift falcon
gray mural
heady iris
#

Explain what you're trying to accomplish. I don't know what you want to do.

warm stratus
heady iris
#

I think you should just use properly structured data.

warm stratus
heady iris
#

use JSON or something

#

way less fiddly than trying to write your own parser

gray mural
warm stratus
gray mural
swift falcon
warm stratus
heady iris
warm stratus
heady iris
gray mural
heady iris
#

made a thread

warm stratus
#

ok i hope it works

gray mural
warm stratus
gray mural
heady iris
warm stratus
#

i guess i am probably wrong

warm stratus
heady iris
#

json is a text file

#

it's just got some structure to it

gray mural
warm stratus
warm stratus
#

oh no that will be pain πŸ‘

#

thks for you help πŸ™‚

heady iris
#

we all did this at some point, lol

#

i wrote a very bad text adventure engine in Java

#

using my own hand-rolled file format

muted schooner
heady iris
#

Singletons are good, as long as they stay single

muted schooner
#

but for my example at least, it is not a very good idea

#

since there may be 2 or 3 players

#

I don't think to add that possibility though

#

but what if I do, I would need to rewrite as you said

heady iris
#

You can still keep the "vibe" of singletons (what a phrase) by having a Player object that references the stuff that would normally be a straight-up singleton

#

of course, at that point, you're basically just doing...normal programming

#

but that's how you'd migrate from singletons to non-singletons

#

rather than a static field, you reference something specific

twin hull
#

@muted schooner as long as you understand how singletons are going to fuck you up down the line, it's fine to use them until at least singleplayer works. and if you're aiming for multiplayer right away, then you'll know how it'll fuck you up right away πŸ˜‚

heady iris
#

ideally, you'll just replace the static reference with a field, and then figure out how to assign the right thing to that field at the start

twin hull
#

need to manage the references carefully though, a beginner's spaghet can be worse than singleton

latent latch
#

You can get away with a lot of stuff with multiplayer and singletons, assuming you've got a single character.

muted schooner
#

I will use singletons only for the basic and static things from now

#

that may be an item database

latent latch
#

Took me a while to get my head around it, but a lot of character code you'd throw into singleton can be clientsided

heady iris
#

Each shrine (save point) is defined by a scriptable object. I load all of those objects from a Resources folder on startup

#

the save file lists the IDs of all of the save points you've made it to

muted schooner
#

yes pretty much makes sense in case the thing is static you are going to use singleton on

latent latch
#

I've tied a bunch of my playable character data, which you'd only have one of at every point of my game, to singletons. I did think about enemies with inventories and such, but I've went a different way with it and just developed drop tables.

#

A lot of these concepts should be declared early on anyway. It's not like I'm going to say tomorrow I want to change it all again.

#

Enemies on the other hand do need independent data so the idea wouldn't work too well with them.

heady iris
#

I try to make the player non-special

#

the only thing that is unique about the player character is that your keyboard tells it to do things

latent latch
#

Yeah, I do try to make stuff reusable when I can, but like when an item drops the only person I want picking that item up is the player anyway.

#

So it makes sense to just use the singleton reference to add it to their specific inventory and be done with it. And, like I was saying before, a lot of this functionality can be client sided so it will work on multiplayer games with the assumption that everyone controls a single character.

hard tapir
#

Help

#
            currentRadius = Mathf.Lerp(targetSizes[currentStep - 1] * startRadius, targetSizes[currentStep] * startRadius, t);
            currentRadiusZone = Mathf.Lerp(targetSizes[currentStep - 1] * 1, targetSizes[currentStep] * 1, t);
            startPosition = transform.position;
            transform.position = Vector3.Lerp(startPosition, targetPosition, t);
            targetZone.position = Vector3.Lerp(startPosition, targetPosition, t);``` Lerp of position is not relative to shrink of scale, currently it looks like it moves instantly to new position and then it starts shrinking
west elk
#

In your experience, whats the best way to serialize a Dictionary?

#

I'm trying to set up some crafting recipes with a material needed key and an int ammount value

leaden ice
hard tapir
#

@leaden ice you are indie or in AAA studio?

leaden ice
#

you need to save the starting position from the beginning

leaden ice
hard tapir
hard tapir
leaden ice
#

the starting position is the starting position. The position of the object changes but it started somewhere

hard tapir
#

It should lerp between previous position and target position

civic geyser
#

hello, may i ask how to use lerp as I still have no clue how to do such

civic geyser
#

I've looked at that

#

and do not understand it clearly

marble halo
#

you can do the same with vectors

civic geyser
#

yeah i wanna use vectors

#

but i dont know how

twin hull
#

@civic geyser you don't understand what lerp is, or how to lerp over time correctly?

marble halo
#

just replace mathf with vector3

civic geyser
#

ok and one more thing

#

lerping over time

#

i want a object to over time move to a set position

#

not just instantly move

civic geyser
#

aighty than

distant goblet
#

I have a general question, not about coding, i hope i'm right here, where can i activate unity collaborata in version 2022.3.3f1?

distant goblet
#

thanks

twin hull
potent sleet
civic geyser
#

plastic scm?

distant goblet
#

whats that?

civic geyser
#

i'll talk in talk channel

hard tapir
#

Here, will this work now? ```float t = (Time.time - shrinkStartTime) / shrinkDurations[currentStep];
currentRadius = Mathf.Lerp(targetSizes[currentStep - 1] * startRadius, targetSizes[currentStep] * startRadius, t);
currentRadiusZone = Mathf.Lerp(targetSizes[currentStep - 1] * 1, targetSizes[currentStep] * 1, t);

if (t < 1f)
{
Vector3 startPosition = transform.position;
float maxDistanceDelta = Vector3.Distance(startPosition, targetPosition) * t; // Calculate the maximum distance to move

// Move the object towards the target position
transform.position = Vector3.MoveTowards(startPosition, targetPosition, maxDistanceDelta);

// Move the targetZone towards the target position
targetZone.position = Vector3.MoveTowards(startPosition, targetPosition, maxDistanceDelta);

}
else
{

transform.position = targetPosition;
targetZone.position = targetPosition;

}

rocky jackal
#

can i save a refrence to a script in any of these types

#

?

prime sinew
rocky jackal
#

but that doesent work with unity netcode

rocky jackal
west elk