#archived-code-general

1 messages Β· Page 374 of 1

pearl burrow
#

btw everything is more clear now thank you all!

#

yeah the levels are just to tell what its coming. So yeah, i'd keep the scriptable objects

untold basin
#

most studios build custom tools to sync their data in an office-local model that everyone can access and back up to with infinite undos (like source control, sometimes it even is just source control)... They use custom tools to automate packaging everything and custom tools for initializing and serializing levels that are compatible with AAA practices for the purpose of compression and optimized load speed for target devices and for mass distribution....

In the end if you're just indie whatever you use doesn't matter :D if it works for you

pearl burrow
#

just an indie working on my first "big expectative" mobile game

#

i wouldnt give my code to anyone.. because its ugly af
ty again!

fringe ridge
#

How performance intensive you think Collider2D.GetClosestPoint is?

hexed pecan
candid star
#

What's easier 2d or 3d?

#

2d right

plucky inlet
#

Is there a way, to get a type and let a class accept is as so?

System.Type type = currentClass.GetType();
Singleton<type>.Instance.SendMessage(currentMethod);

Is giving me currently 'type is a variable but used as a Type'

knotty sun
candid star
#

For a new coder is 3d easier?

knotty sun
#

Ja

thick terrace
maiden ingot
#
Physics2D.IgnoreCollision();

This uses like "Colliders" but, can i ignore the collision of a group of things? like:

if(enemyHit){
//disable the collisions between you and ALL the enemies, not only the one who hurt you
}
#

i was trying to access to this but it seems like i cant

rigid island
plucky inlet
thick terrace
plucky inlet
#

MonoScript.Getclass itself is part of UnityEditor, so cant use that to call the methods from the runtim Instances

thick terrace
#

which part are you trying to do at runtime then?

#

none of the MonoScript stuff will work in a build

hexed pecan
#

The whole monoscript class is editor only

plucky inlet
#

So I am passing in the asset to the editor script, which holds the method string to call for. What I now need is the string to the actual class type, so I can once at runtime get the instance and call the methods from there

edgy bough
#

Is it possible to set custom mesh renderer bounds? The docs say that the field MeshRenderer.bounds cannot be overwritten, at least in 2019.3

thick terrace
#

so like Type.GetType?

plucky inlet
#

In the end, I had this more or less hardcoded

Singleton<XRAdminManager>.Instance.SendMessage(currentMethod);

And I want this method to get the dynamic XRAdminManager from the object I stored when assigning the monoscript in editor

#

Its just personal preference of dynamic code. If its not working at all, I just use a simple switch case

thick terrace
edgy bough
thick terrace
edgy bough
#

I cannot change versions since this is for a Kerbal Space Program mod

plucky inlet
plucky inlet
# thick terrace so like `Type.GetType`?

Kind of. In the end, I want to find the instance of a class in runtime which I somehow stored in editor at least the class or whatever I can find via runtime.

thick terrace
# plucky inlet Kind of. In the end, I want to find the instance of a class in runtime which I s...

iirc if you store the full name of a type from the editor reference (https://learn.microsoft.com/en-us/dotnet/api/system.type.assemblyqualifiedname?view=net-8.0#system-type-assemblyqualifiedname) you should be able to fetch it at runtime with GetType

Gets the assembly-qualified name of the type, which includes the name of the assembly from which this Type object was loaded.

plucky inlet
knotty sun
warm badger
#

with empty scene, untracked memory is very less, when i am importing assets, then after using those in scenes, creating those untracked memory even if i unload? what can be the solution then?

plucky inlet
plucky inlet
#

I mean, if there is a better way to get instances of a class at runtime dynamically, I am totally open minded.

warm badger
plucky inlet
sly chasm
untold basin
#

it's easier for our brain to conceptualize 2D world than 3D math imo

candid star
#

I will start with 2d tmr cause today I spent to much Time

untold basin
candid star
untold basin
#

I would say you need to evaluate what you want to do and come to an understanding of how long it's going to take :) For this goal I would recommend:

  • fundamentals in illustration, lighting, both traditional and digital (take some courses)
  • learn the math involved in pixel art!
  • follow lots of tutorials on creating art in general
  • learn Unity fundamentals (through the tutorials I linked earlier)

basically I would say in order to actually take on the project of making a game, you pretty much need the knowledge and experience to do it intuitively.

If you want a more simple, easy route check out rpg-maker. Also might wanna move this discussion to a more general channel.

sly chasm
spare dome
tawny elkBOT
#

:teacher: Unity Learn β†—

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

candid star
#

Alr thx

pure ore
#

What is the best way to learn how to code? I know people are probably going to say documentation, but so what, do people just look up loads of documentation, and then string up their code with documented code hoping it'll work?

#

like combining code documentation?

spring nacelle
#

The best way to learn how to code is to start with something you want to do or make, then research the skills you need as you need them

inner shuttle
#

bump

spring nacelle
#

There are myriad tutorials for anything you may want to do

pure ore
#

I don't want to really do tutorials, I want to come up with my own code, plus tutorials don't teach you much beyond doing it how they do

spring nacelle
#

unless you're willing to take classes and learn directly from someone else helping you, tutorials are the only other real way of doing it

leaden ice
spring nacelle
#

you aren't going to learn code by brute force or by putting your head into the documentation

#

You start with tutorials, then modify them to suit your needs

leaden ice
#

Documentation is reference material, not learning material

pure ore
#

oh no? I thought it was as simple as taking Mathf.Deg2Rad in the documentation, looking up what is does, and adding that into your code

leaden ice
spring nacelle
#

even me, who's been doing this for years, still uses tutorials for things I don't know. Though I spend much less time iwth them

leaden ice
#

You can and should do this

#

But that won't teach you those principles, like what a function is and how to call it

untold basin
pure ore
#

But I don't understand, tutorials are limited, let's say you find a tutorial for a basic character controller, but your game needs something more, how do you figure out how to expand it programming wise?

untold basin
#

if you want to do everything from scratch with no help AND you don't know how to code, GL I guess ? There's a huge resource for !learn ing how to use unity

tawny elkBOT
#

:teacher: Unity Learn β†—

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

untold basin
spring nacelle
leaden ice
spring nacelle
#

figure out why the character controller you got from the tutorial does or doesn't work, then change it

leaden ice
#

But looking at examples is a starting point and yes you would combine this with reference material to come up with a solution

pure ore
#

So basically just throw anything at the wall until it works?

leaden ice
#

No...

spring nacelle
#

no

pure ore
#

Sorry guys, I have a learning disability so its hard for me to understand

subtle cradle
#

Anybody out there using VSCode (with Gemini)? any tips for prompt engineering?

leaden ice
#

A learning disability certainly adds challenge

#

Tutorials etc build up your base knowledge of what's possible and how

#

And may provide inspiration or a starting point for code and scene setup

pure ore
#

So let's say I wanted to add physics. I know that Vector3.up means down, so I would do m_SomeVector = Vector3.MoveTowards(m_SomeVector, Vector3.up, m_Gravity * Time.deltaTime);

spring nacelle
#

when you say... 'add physics' what do you mean? do you just want things to respond to gravity?

pure ore
#

Yes

#

I.E my player

spring nacelle
#

Does your object have a rigidbody on it?

pure ore
#

I use character controllers

leaden ice
pure ore
#

okay so what is it?

leaden ice
#

It's up

pure ore
#

Oh so I would do -Vector3.up

leaden ice
#

Vector3.down

spring nacelle
leaden ice
#

Or yes that

pure ore
#

Because I had it go up not down

leaden ice
leaden ice
pure ore
leaden ice
#

I think you need to slow down a little and think about what your code means. You might be rushing and not understanding.

pure ore
#

Yeah. here's the thing

#

So there's this game called Bendy and the Ink Machine, I talked to the programmer on that, and he even held a press conference at a location I forgot, but he said he learned to code by googling "how to do this in unity" the only thing I don't know was how he expanded it for the sequel

naive swallow
#

The next step is to actually do that thing in Unity, see what went wrong, and remember that for future use

pure ore
#

@leaden ice Vector3.up has to mean down because when I negate it, the player goes up

simple egret
#

Depending on what you're using, the player itself might be upside down

#

Make sure its local Y axis (green) points up

#

Some methods will convert your vector to local space before applying it, like transform.Translate

pure ore
#

nvm it was an issue with another float value I was using

leaden ice
warm badger
#

those who used addressables, did you ever face untracked memory growth while using scene load and unload? i am trying to figure out what could be the reason, can't see any light at all. i am thinking is it any device specific problem? i don't have any other other device except my pc right now, not even a mobile. can anyone help me to get my sample test project shared to see if you too are getting the untracked memory? this could give me relief whatever the result comes. sorry to bring such topic here

cosmic rain
warm badger
#

i will share the file link soon

cosmic rain
#

My guess it's just part of unity implementation and there's nothing you can do about it.

warm badger
#

yeah that might be true, but look at my screenshot from memory profiler window, first one is before scene load, second one after scene load, last one after unload. even after unloading memory only goes down 3mb, then where is the benefit of using addressables to unload things to free up memory. I think i am wrong with my project somewhere, I am really grateful that you agreed to help me. please look into it a bit.

warm badger
cosmic rain
# warm badger yeah

Did you try loading/unloading multiple times? Does it keep on increasing by ~50mb every time?

#

If not, it could just be unity reserving the memory and reusing it afterwards.

warm badger
#

sometimes more again sometimes less

cosmic rain
#

Well, I'll have a look when I get back, but don't get your hopes up. I can only use the same tools that you do, so it's unlikely I'll figure out something new.

#

Might be a good idea to post on the forums. Perhaps some unity staff would see it.

warm badger
warm badger
cosmic rain
#

Possible memory leak with addressables?

candid star
#

i spent 2 hours yesterda trying to code a working movements script in 2d en 3d and it didnt work😭

knotty sun
plucky inlet
knotty sun
plucky inlet
stone rock
#

Hello, i have a script holding a reference to a generated input actions class from the input actions asset.
When i adjust a script during playmode the instance or reference to it seems to be gone.

_inputActions = new InputActions();

Is the code i have for creating an instance.
Could it be this instance is deleted when Unity reloads a script during playmode after adjusting it?
Are there methods that do get called when it's being reloaded to make sure it works flawlesly in the editor too?

knotty sun
lean sail
stone rock
knotty sun
stone rock
#

Is it a good idea to just put it in OnEnable()? Right now the instance creation and setcallbacks function is in Awake and only the .enable is in OnEnable()

stone rock
candid star
compact perch
#

Doing both at the same time will be too confusing ig, and 2hrs is nothing like Steve said. But it's nothing for one type of movement. For 2 types it's less than nothing :p

candid star
compact perch
candid star
#

So should I start 2d then?

compact perch
#

That depends. If you want to do 3d in the future, you can start with 3d (or 2d to get the basics then move to 3d), it's all about what would be more comfortable for you. But if you like 100% sure that you want to do for example only mobile 2d apps, you don't need to know 3d at all

candid star
#

True

#

I like 3d more so I will do that

compact perch
#

So prepare to learning about quaternions and matrices asap :p in 2d you need only sin and cos.

hexed pecan
compact perch
#

Shaders as a whole, but right, it's not general programming. I found them helpful to understand quaternions tho

plush bobcat
#

Working on a racing AI using ML Agents. I don't know what I'm doing wrong, I'm implementing what i'm seeing in YT videos almost 1:1 to no avail. What relevant information should I send to get help for this?

leaden ice
cobalt bloom
#

I'm generating a mesh for my voxel grid, but I want my voxels to be able to be multiple materials. Do I have to generate separate meshes for every material?

rigid island
leaden ice
#

you could also use multiple submeshes and multiple materials, yeah

cobalt bloom
#

like some voxels will be glowy and stuff

leaden ice
cobalt bloom
#

Submeshes still use multiple draw calls tho ;(

#

I think?

leaden ice
#

If you want different materials there are absolutely no way to avoid multiple draws

cobalt bloom
#

How do I generate submeshes

cobalt bloom
#

I'm drawing the mesh using the Graphics.DrawMesh. Do I have to use a MeshRenderer for this, or can I just generate separate meshes instead of using the submesh stuff.

finite ferry
#

I have a script that from time to time stops working, or I guess "updating". It stops working when I make changes in other scripts but starts working again when I make changes in it. I have no idea why it acts like this and it drives me crazy since I've already spent hours trying to fix the problems that this causes. But it wasn't until recently that I understood that this script was the root of the problems.

FYI: The script is a public class that doesn't derive from MonoBehaviour and I do not get any errors from it, whether working or not.

#

(With "make changes" I mean typing something, anything, and saving).

#

This is the script:

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

[Serializable] public class Cooldown
{
    [SerializeField] private float _cooldownTime;
    private float _nextFireTime;





    public bool IsCoolingDown()
    {
        return Time.time < _nextFireTime;
    }

    public void StartCooldown()
    {
        _nextFireTime = Time.time + _cooldownTime;
    }
}```
leaden ice
#

that's the point of it - to render meshes without a MeshRenderer

#

Also RenderMesh is the newer API

cobalt bloom
#

nono I know

cobalt bloom
#

RenderMesh doesn't exist

#

anyway, I meant that does Graphics.DrawMesh support multiple materials? If so, how do I give them to it

leaden ice
#

It would be one DrawMesh call per Material/SubMesh

cobalt bloom
#

o yea

somber nacelle
#

!code

tawny elkBOT
narrow summit
#

long shot, but does anyone know a chess AI which supports, more than normal chess pieces on the board, and a configuarable chess board itself [i.e. missing tiles]?

open plover
#

or a bigger board like 12x12

narrow summit
calm mountain
#

I've tried the firebase help discord, but it is so incredibly inactive and unhelpful:
Using firebase with Unity, my client crashes when I try to login.
The conditions that cause this are when someone is already successfully logged in and then someone else tries to login. This 2nd person's client crashes

        public async Task<bool> Login(string _email, string _password)
        {
            try
            {
                Debug.Log("Bruh 1");
                // Call the Firebase auth signin function passing the email and password
                var loginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);
                Debug.Log("Bruh 2");
                // Await until the task completes
                await loginTask;
                Debug.Log("Bruh 3");

                User = loginTask.Result.User;
                Debug.Log("Bruh 4: " + User.UserId);
                DocumentReference docRef = DBreference.Collection("users").Document(User.UserId);
                Debug.Log("Bruh 5");

My crash logs never make it to the Bruh 5 debug log, but successfully shows the correct User.UserId. Any ideas?

simple egret
#

Check the logs and post the part where it crashes. You may be getting an exception

#

!logs

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

calm mountain
#

No errors

simple egret
#

Also since you await the task, it's a bit weird to use .Result here

var result = await loginTask;
User = result.User;

Does the crash still occurs if you remove the line between logs 4 and 5? Same question with wrapping it with a try/catch and logging if there's an exception

calm mountain
plucky inlet
#

If you start the task in background, you cant use debug.log and other unityengine methods

calm mountain
calm mountain
plucky inlet
#

do you get the debug.logs "bruh " ?

simple egret
#

Up to the 4th

#

See if there's a non-async alternative, even if it freezes the game for a bit, just to rule out a threading issue

#

Unity will silently terminate a "background" thread that accesses Unity stuff

plucky inlet
#

But as he gets the other debug logs, I guess its not the issue here

plucky inlet
somber nacelle
plucky inlet
#

Thats why I am using this thing to actually log in tasks/awaitables on background threads

 static public async Awaitable LogQueue(object message, Object context = null)
        {
            Dispatcher.Enqueue(() =>
            {
                if (context != null)
                    Log(message, context);
                else
                    Log(message);
            });
            await Awaitable.MainThreadAsync();
        }
calm mountain
# plucky inlet What is loginTask actually doing?

First it authenticates the user's credentials, then accesses firebase to get the user's account info like username, customized character, saved spell loadouts etc then it proceeds to allow the player to the main menu

plucky inlet
somber nacelle
plucky inlet
thick terrace
#

yeah the context parameter will definitely cause problems on other threads, but the non-context one is fine

thick terrace
lilac thistle
#

has anyone here used the Simple LUT Adjuster from Jeff Johnson?

plucky inlet
thick terrace
plucky inlet
thick terrace
#

that doesn't matter

#

what you wait for inside an async method has no effect on its callers

plucky inlet
#

if I await for the async method to be finished does

thick terrace
#

if your method runs on a worker thread but is awaited from the unity thread, the caller will return on the unity thread

somber nacelle
#

i honestly don't even see the point in wanting to await the LogQueue method in the first place. it should just be a normal synchronous method that enqueues the log call and that's it

calm mountain
#

Ok, I've got somewhere

pure ore
#

Anyone know how to fix this?

plucky inlet
thick terrace
somber nacelle
#

there is no guarantee here that the log has even printed yet, the only guarantee is that it has been enqueued to your dispatcher queue

plucky inlet
somber nacelle
#

if that is what you want to happen, why is that the responsibility of a method that is just supposed to queue logs to print?

plucky inlet
somber nacelle
#

but even still, awaiting MainThreadAsync does not guarantee that your log has actually printed by that point as that is entirely up to how and when your dispatcher prints the logs

calm mountain
#
        public async Task<bool> Login(string _email, string _password)
        {
            try
            {
                // Call the Firebase auth signin function passing the email and password
                var loginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);
                // Await until the task completes
                var result = await loginTask;
                User = result.User;
                Debug.Log("Bruh 4: " + User.UserId);
                /*
                DocumentReference docRef = DBreference.Collection("users").Document(User.UserId);
                Debug.Log("Bruh 5");
                
                string playerUsername = "";
                var snapshot = await docRef.GetSnapshotAsync();
                Debug.Log("Bruh 6");

                if (snapshot.Exists)
                {
                    Dictionary<string, object> userData = snapshot.ToDictionary();

                    playerUsername = userData["name"].ToString();
                }
                else
                {
                    Debug.Log("Document does not exist!");
                }
                
                LobbyNetwork.FireBaseUID = User.UserId;
                //LobbyNetwork.FireBaseToken = await auth.currentUser.TokenAsync();
                _signInMenu.SetSignInLocked(true);
                LobbyNetwork.SignIn(playerUsername);
                _characterMenu.LoadCharacterFromDB();
                _spellSelectMenu.LoadSpellsFromDB();
                */

                LobbyNetwork.FireBaseUID = User.UserId;
                _signInMenu.SetSignInLocked(true);
                LobbyNetwork.SignIn("Nate");
                _characterMenu.LoadCharacterFromDB();
                _spellSelectMenu.LoadSpellsFromDB();
            }
``` ok well this still crashes so I guess I'm still searching lol
plucky inlet
plucky inlet
# somber nacelle but *even still*, awaiting MainThreadAsync does not guarantee that your log has ...

From what I experienced, it is exactly doing that, guarantee that I get the correct order
The first one logs in the wrong order. It fires test me before the enqueued log. In this case, its expected, but I have nested tasks where the logs got messed up and I wanted to have a clean understandable logging of what is going on.

 await Debug.LogQueue("AR Supported: " + arSupported + ". Fallback to non tracked runtime.", this);
Debug.Log("Test me");

This one logs correctly one after the other

await Debug.LogQueue("AR Supported: " + arSupported + ". Fallback to non tracked runtime.", this);
await Debug.LogQueue("Test me");
#

This especially was an issue, when I needed to access unityengine parts in background, so I had to enqueue and wait for the mainthread , then continue

somber nacelle
#

that's not really related to you awaiting that method though, that's because of the fact that you are queueing your logs with a queue then presumable dequeueing them in that same order on the main thread

plucky inlet
#

And also, the object, as you mentioned, was causing issues, so both issues made me do the enqueued log.

simple egret
#

Would using a TCS solve this? Maybe the timing issue at least

Task LogAsync(string message)
{
    TaskCompletionSource tcs = new();
    Dispatcher.Enqueue(() =>
    {
        // ...
        tcs.SetResult();
    }
    return tcs.Task;
}
plucky inlet
somber nacelle
somber nacelle
plucky inlet
simple egret
#

Completing the task in the Enqueue method will stop the caller from awaiting. At this point your log should be printed and the execution will resume past the await

plucky inlet
#

So the Awaitable.MainThreadAsync() is not actually awaiting for mainthread and then continue?

somber nacelle
plucky inlet
simple egret
somber nacelle
simple egret
#

This would ensure the log is ran on the main thread, if I understand the API correctly

await Awaitable.MainThreadAsync();
Debug.Log("hello", obj);
plucky inlet
plucky inlet
simple egret
#

The caller's context won't switch to the main thread IIRC, each async method has its own context

plucky inlet
simple egret
#

Given that you await the task, yes

somber nacelle
fossil blaze
#

Hi guys

#

How do I get and output this data to Unity from Telegram?

plucky inlet
# somber nacelle but why would you *want* the caller to be paused for that? if the only point was...

I just removed the dispatcher enqueue entirely and just used the awaitable mainthread method to log after that. Still need to wait for the log, because I want, as said already, my logs to be in correct order. Task doing something in background, starting another task that checks on whatever, doing some log too. If I let them all just log together on the mainthread, it would just be a random order of logs at whenever the mainthread is cycling. Thats why I was waiting for the mainthread in the log. And as expected its working as before, but makes more sense now as you guys stated to not await and then do nothing. Thanks for your input and suggestions!

plucky inlet
somber nacelle
#

well now you're just potentially slowing your code down even more when you continuously hop from background threads to the main thread. and even then, why not just do the work on the main thread in the first place if you don't care about needing to do so? the dispatcher already controlled the order of the logs as i've described to you countless times at this point. you just refuse to understand that for some reason, all you needed to do was make that LogQueue method return void and no longer be async and it would have worked just as well as it already was, but without the pointless awaiting

plucky inlet
somber nacelle
#

i'm not saying you can't use async for other things. i was simply pointing out that LogQueue has really no reason at all to be async if you were just enqueueing the logs to be printed on the main thread

calm mountain
# plucky inlet I still think, its your loginTask, causing issues

Why do you think that? I've made some workarounds to be able to proceed around my DocumentReference docRef = DBreference.Collection("users").Document(User.UserId); line, which is my suspected crash point.

But now it proceeds to two other spots that call something very similar and crashes there. Commenting those out allows me to proceed without crashes

plucky inlet
calm mountain
#

When I try to log the collection, it crashes there :/

calm mountain
plucky inlet
calm mountain
plucky inlet
calm mountain
plucky inlet
calm mountain
#

oh wait, one sec

calm mountain
#

And again, this works if only one account logs in. It is once the 2nd one logs in while the first is still logged in that it crashes

#

So it could be some sort of one-time-use session token being used but I have no clue what I'm doing here lol

plucky inlet
calm mountain
#

Printing the Debug.Log("Bruh 4: " + User.UserId); shows a the different users

plucky inlet
calm mountain
somber nacelle
calm mountain
somber nacelle
#

well that's not very helpful for debugging purposes. why not catch (Exception ex) and then print the actual exception?

calm mountain
plucky inlet
calm mountain
#

And my current one is a FirebaseException

plucky inlet
calm mountain
covert grove
#

Do you guys know what version of C# will be used for unity 6?

calm mountain
somber nacelle
covert grove
#

Oh okay thank you

dim umbra
#

what's the best way to make an object follow another object's movement but with a multiplier?

#

so if object A moves 10 units, object B would make the same movement at half speed and move 5 units

vagrant blade
#

Multiply the speed of the object by a scalar value, such as 0.5 for half the speed.

#

For following, entirely depends on how you're moving things. You want a straight line? Just move it towards it via MoveTowards(...)

dim umbra
#

yeah, probably should have mentioned that it doesn't use velocity

#

trying to make a parallax background

#

here's the (relevant) camera movement code

            if(Vector2.Distance(targetPos, transform.position) < 1f && Vector2.Distance(targetPos, transform.position) > 0.01f){
                speed = 1/Vector2.Distance(targetPos, transform.position);
            } else {
                speed = 1;
            }
            
            if(Vector2.Distance(targetPos, transform.position) < 0.01f){
                transform.position = targetPos;
            }
#

don't remember the way to make that c sharp formatted

vagrant blade
#

Multiply your final speed by some scalar value

#

But if you want it to be a % of the target speed, it really should just take the speed of the target rather than calculating its own and multiply against that?

dim umbra
#

I don't understand what you're trying to say

#

I want the object to move at a fraction of the camera's movement

vagrant blade
#

You want ObjectB to move the "same movement" as ObjectA but half the speed. So get the speed of ObjectA and multiply it by half.

dim umbra
#

i thought there would be some shortcut for this but i guess if that's the only way, i'll do it

#

it's just annoying because of the code that adjusts the camera not based on speed

#

so i'll have to recreate that for the other object

leaden ice
dim umbra
#

oh, yeah that probably works

#

I'll try

#

yep, works perfectly

#

thanks

untold crystal
#

how do i make dynamic rigid body not flip in unity 2d i want my charechter to not fall and flip

maiden fractal
#

also please ask only on one relevant channel

wispy depot
#

Hi! I'm trying to make sort of a modular system, with a class for each different module. I have an issue though, that if a class inherits from another class, I don't seem to be able to have that class have some variables different from the parent class? Example:

public class ModifierTemplate : MonoBehaviour
{
    public int multMultiplier = 0;
    public int numMultiplier = 0;
    public int flatMult = 0;
    public int flatNum = 0;
    public bool addNumberToNum = false;
    public bool addNumberToMult = false;

    public void triggerModifier(GameWheel wheel, NumberTemplate number)
    {
        wheel.mult += flatMult;
        wheel.num += flatNum;

        wheel.mult += (wheel.mult * multMultiplier);
        wheel.num += (wheel.num * numMultiplier);

        if (addNumberToNum){wheel.num += number.number;}
        if (addNumberToMult){wheel.mult += number.number;}
    }
}

public class x2Mult : ModifierTemplate
{
    
}

In this example, I wan't the x2Mult class to inherit the modifiertemplates triggerModifier function, and it's variables, but I would want for the "multMultiplier" variable of the x2Mult class to be different from the modifiertemplates class.

How do I do that?

knotty sun
wispy depot
knotty sun
#

otherwise

public class x2Mult : ModifierTemplate
{
    public override int multMultiplier = 1;
}
wispy depot
#

Oh, I need to use the override! Thanks! Massively helpful, I didn't even know override existed.

knotty sun
#

and

public class ModifierTemplate : MonoBehaviour
{
    public virtual int multMultiplier = 0;
wispy depot
#

Thanks!

wispy depot
knotty sun
#

oh, try this

public class ModifierTemplate : MonoBehaviour
{
    public int multMultiplier = 0;
...
public class x2Mult : ModifierTemplate
{
    public new int multMultiplier = 1;
}
wispy depot
#

I think that works, yes. Though rider is telling me the x2Mult's "multMutliplier" variable isn't being used, is it supposed to be like that? Is that a quirk of Rider or does it mean that it won't work?

knotty sun
#

that's rider gatekeeping

wispy depot
#

Thanks!

knotty sun
wispy depot
knotty sun
#

oh dear, sounds like you need some basic C# learning.
abstract means that the class itself cannot be instanced but classes that derive from it can. It's a kind of protection ideal for 'Template' classes

wispy depot
knotty sun
#

then you should be able to make the variables virtual and the method virtual as well

wispy depot
#

As for the learning bit, that's why I'm on this discord, isn't it? I will admit though, my knowledge of C# is quite holey, as most of my learning has been from figuring it out myself and using stackoverflow

knotty sun
wispy depot
wispy depot
lean sail
#

Virtual would be for methods or properties.

lean sail
wispy depot
#

There will be other classes inheriting from the modifierTemplate class that will need a different formula/method though

knotty sun
lean sail
wispy depot
lean sail
wispy depot
lean sail
#

And again because these are monobehaviours you dont need another script for this. You assign the value in inspector. The only thing this changes is the default value when you create the script

wispy depot
lean sail
#

Is there a reason you're using monobehaviours then?

knotty sun
wispy depot
lean sail
#

I assumed you were planning on using AddComponent at runtime, which isnt common at least from what I've done

knotty sun
#

you can only instance a MonoBehaviour using AddComponent

wispy depot
#

Thinking about it, I suppose I don't need them to be monobehaviours - that was just me not thinking about it

lean sail
#

Yea this could probably just be it's own plain c# class and youd save a bit of performance if theres a ton of modifiers

knotty sun
#

and, it will follow the rules of C# not the rules of Unity

wispy depot
#

Yeah I did that now

lean sail
#

Though I still do find it unnecessary to create a whole new class just for a default value to change. When you create an instance of that base class, all those values are 0. Surely you plan to assign some values to those modifiers. Maybe itd be better if you just change the formula in the x2 multiplier class instead

wispy depot
lean sail
# wispy depot It is necessary because of how other aspects of the game is structured. I could ...

That last point was less about performance. It's more about how you're going to be assigning a value to this class somehow when its new()'d. Maybe in the constructor, maybe just by changing the public variables. If you dont do this then well all the values are 0 using the base class.
Now if you want to use the x2 multiplier class, this would imply you're now using the default values. If you assign the values like you will be doing using the base class, then theres no point in having a different default value.

#

And if you're creating an instance of this derived class, you already know it's supposed to be a 2x multiplier so you could just assign it larger values. Or use the constructor, pass it in a value, and it automatically multiplies it by 2

plucky lance
#

Anyone got a good tutorial for a rts style system

main shuttle
# plucky lance Anyone got a good tutorial for a rts style system

Way too broad a question, what part of RTS style system?
Some general overview, I liked: https://medium.com/codex/making-a-rts-game-1-placing-buildings-unity-c-c53c7180b630
Rather long and textual tutorial though, and not at all best practices, just basics.
Just creating good pathfinding, like in SC2 is a full time job in and off itself.
If you want to make Supreme Commander/BAR type game, you need to do things very different.
So we don't really have a way to give you a 'good tutorial'.

whole night
#

when i run webgl build and start server using netcode for game objects, it gives error:
Exception: WebGL as a server is not supported by Unity Transport, outside the Editor.

somber nacelle
#

#archived-networking
But also, that is accurate. you cannot use the unity transport on webgl unless you use the netcode for gameobject 1.2.0 version (or higher) with the unity transport version 2.0.0 (or higher). so presumably you are using an older version of one of those packages

#

oh and don't crosspost. you originally posted in networking whihc was the correct place to do so

whole night
#

i can only see 1.1 in package manager for netcode for gameobjects

somber nacelle
#

what version of unity are you using?

whole night
#

2022.3.49f1

somber nacelle
#

show what you see in the package manager then

whole night
somber nacelle
#

that's 1.11 not 1.1

#

and last time i checked 11 > 2. so the issue is likely the transport version

whole night
#

Oh, i thought 1.2 > 1.11, my bad

somber nacelle
#

no these aren't decimal numbers, they are semantic versioning numbers.

whole night
#

i am also using 2.3 of unity transport still getting that error

somber nacelle
#

isn't the latest version of the transport 2.2.1? πŸ€”

whole night
#

no its showing me 2.3

somber nacelle
#

huh, docs must not be up to date then. in that case, provide that information in your message in #archived-networking and wait for someone to answer you there

plucky lance
main shuttle
plucky lance
#

Ok thank you!

plucky inlet
#

Is anyone in here using the latest webrtc pre package and knows the fix of the missing plugin registration causing this on build?

The type or namespace name 'WebRTC' does not exist in the namespace 'Unity' (are you missing an assembly reference?)
plucky inlet
#

I am on apple silicon, which seems to be causing the issue

ionic mist
#

Quick question for the AI folks:
Are there AIs that I can integrate into my Unity project to look at the code and answer me questions like "which script does such thing?", etc?
I basically want to avoid the problem of returning to old projects and not remembering what things do what
at the moment, only looking at scripts would be enough for now. Extras are welcome thought πŸ˜›
I'm also willing to write descriptions in my scripts (as commented code) explaining what it does if it's useful for the AI

rigid island
knotty sun
#

tbh I cannot even imagine what it would be like to not remember my own code

sly gate
#

Im currently adding a moba like progression to a prototype im making, with items that increase your stats and add special effects to your attacks or abilities, im thinking ill implement this by keeping an inactive prefab of each attack and ability on the player as a child, and duplicate them when i need to actually spawn them, and whenever an item is bought that adds an effect, i add a script that applies said effect to the inactive prefabs at runtime

how viable is this solution?

tired summit
#

Anyone got any tips for adding a webgl into a web app built on rust with dioxus?

knotty sun
knotty sun
#

tbh I'm amazed that anyone building a web app would not know that

tired summit
#

Way beyond my wheelhouse, but I've learned a lot and it's fun lol

modern creek
#

My game has some calls to Camera.ScreenPointToRay(Input.mousePosition) that is spamming up the console when I start with "Screen position out of view frustum (screen pos inf, inf) (Camera rect 0 0 2560 1440)" messages until I click on the game window. It's not an exception, it's just an error log message, but it's a little annoying. How do I get the "view frustrum" from the camera..? Or do I just need to check for Input.mousePosition.x or .x == infinity? I couldn't find what I need in the API docs for Input and Camera

#

(do I just compare mouse position to Vector3.positiveInfinity?)

modern creek
#

(I just added the lines at the top with all those guard clauses)

#

The line in question is the Ray ray = Camera.main ... line

#

Input.mousePosition reports as positiveInfinity until I move it somewhere in the game window.. after that it's fine

rigid island
#

did you change anything on the camera?

modern creek
#

Whatcha mean? I changed lots of things πŸ™‚ but I'm using cinemachine for some custom zooming/tilting

rigid island
#

can i see the main camera component RQ when this error happenes

modern creek
#

sure, lemme comment out those guard clauses.. sec

somber nacelle
#

this is likely just a quirk of unity not capturing the mouse for the game view until the game view is manually focused

modern creek
modern creek
rigid island
#

oh okay position all looks good, so yeah prob what box said but I have no clue it doesn't happen to me

somber nacelle
modern creek
#

it only happens if I start the game in Scene view, btw

#

I could do that too.. although I'm not sure if that's gonna have weird effects if the user has their mouse in the middle of the screen then alt tabs out.. like.. I'm doing a lot of the input handling manually for map drag/tilt

#

map drag/scroll wheel = pan & tilt

somber nacelle
#

wrap it in conditional compile so it's only included in the editor

modern creek
#

well, it might happen in the web too.. in fact it might almost be guaranteed to happen in the web? I'm not sure if the applet is gonna have focus by default

#

I'll check into it.. I might need to have the user click on the applet to start anyway so I am guaranteed to capture input

somber nacelle
#

don't crosspost

solemn ember
#

sup gang

#

would it be better to have a for loop for this?

#
//Set Verified Decks List
_allDecks = decksToLoad;
_totalPages = Mathf.RoundToInt(_allDecks.Count / 5) + 1;

Debug.Log("Total Decks: " + _allDecks.Count);
Debug.Log("Total Pages: " + _totalPages);

//Instantiate all decks buttons
foreach (DeckSO deck in _allDecks)
{
    //Set page transform,
    //5 decks per page
    Transform pageTransform = transform;

    int currentDeckIndex = 0;
    var butt = Instantiate(_deckButtonPrefab, pageTransform);
    butt.GetComponent<Button>().onClick.AddListener(() => SelectDeck(currentDeckIndex));
    butt.GetComponent<Tooltip>().SetToolTipMessage(deck.Description);
}```
#

I have a list of decks, which it will create a page for every 5 decks

rigid island
#

as oppose to what?

solemn ember
#

for each page, it will instantiate a button (up to 5) for each deck

rigid island
#

the only thing I would change mainly is the AddListener and also make it its own class that has already those as props

solemn ember
#

I'm instantiating this

#

a for loop, to count on the deck index

rigid island
#

I can see that. But you can skipp add Components if you already had those assigned as props

#

and AddListener, I rather use an actual method assigned to it so I can clean it up

solemn ember
#

my add listener is fine

#

I want to focus on the ID

#

every time I instantiate a deckButton in the list, I want to assing an ID to it

rigid island
#

so whats stopping you?

solemn ember
rigid island
#

you have to increase the index you can't define it in the loop or you keep overwriting it with 0

solemn ember
#

I'm trying to figure out how to get the index

#

oh

#

so I need to make an int, outside of the loop

rigid island
#

if you plan on increasing it each iteration, sure

solemn ember
#

yes

rigid island
#

also why not just use a for loop in that case

solemn ember
#

okay let me see what I can do

solemn ember
#

that's what I was asking

#

xD

#

if it was better

rigid island
#

I wasn't sure why you asked if a for loop was better sorry

solemn ember
#

^ all good

#

let me try this with whawt I have and

#

I'll come back with results xD, good or bad

modern creek
#

When you resize the browser, is there any way to hook into unity? The canvas I'm using is getting physically shrunk but I'm not getting changes to Screen.width or height

solemn ember
#

messy, but it works

#

@rigid island

#
void LoadAllDecksInList()
{
    int deckIndexInLoop = 0;
    List<DeckSO> decksToLoad = new();

    //Clear All Pages and Decks List
    _allDecks.Clear();
    _deckPages.Clear();

    foreach (Transform page in _deckPagesHolder)
    {
        Destroy(page.gameObject);
    }

    //Add all existing decks
    foreach (DeckSO deck in CardsLibrary.Instance.BasicDecks)
    {
        decksToLoad.Add(deck);
    }
    //Also load custom decks here

    //Verify if decks are valid

    //Set Verified Decks List
    _allDecks = decksToLoad;
    _totalPages = Mathf.RoundToInt(_allDecks.Count / 5) + 1;

    //Instantiate all pages
    for (int i = 0; i < _totalPages; i++)
    {
        var page = Instantiate(_deckPagePrefab, _deckPagesHolder);
        page.name = $"Page {i}";
        _deckPages.Add(page);
    }

    //Instantiate all decks buttons
    foreach (DeckSO deck in _allDecks)
    {
        Transform pageTransform = _deckPages[Mathf.RoundToInt(deckIndexInLoop / 5)].transform;

        var butt = Instantiate(_deckButtonPrefab, pageTransform);

        butt.transform.Find("Deck Leader").GetComponent<Image>().sprite = deck.DeckLeader.LeaderImage;
        butt.transform.Find("DeckName Text").GetComponent<TextMeshProUGUI>().text = deck.DeckName;

        butt.GetComponent<Button>().onClick.AddListener(() => SelectDeck(deckIndexInLoop));
        //butt.GetComponent<Tooltip>().SetToolTipMessage(deck.Description);
        butt.GetComponent<Tooltip>().SetToolTipMessage($"Index: {deckIndexInLoop}");

        deckIndexInLoop++;
    }

    _currentPage = 0;
    UpdateSelectedDeckPage();
}```
#
void UpdateSelectedDeckPage()
{
    foreach (var page in _deckPages)
    {
        if (page != _deckPages[_currentPage])
            page.SetActive(false);
        else
            page.SetActive(true);
    }

    _currentPageText.text = $"{_currentPage + 1}/{_totalPages}";
    _nextPageButton.interactable = _currentPage + 1 >= _totalPages ? false : true;
    _previousPageButton.interactable = _currentPage == 0 ? false : true;
}```
#

they're instantiated properly and I can select them

#

which is nice C:

#

nvm

#

the listeners are not being added properly, one sec

#

I'll try with this forloop, if not I'll do it outside like you said

#

it's supposed to be 5... :/

#

which I find weird

#

cause the index in the tooltip message is assigned correctly

#

see, it's getting "5" in the index

midnight sun
#

Can someone explain how you're supposed to query an input on a specific device using the new input system?

rigid island
solemn ember
#

got you

#

well I did this

#

and now it works

rigid island
#

yes i was going to suggest to capture the variable first

rigid island
#

Well normally you would use events instead of polling

#

thats the main benefit of inputsystem

solemn ember
#

πŸ‘€

short quiver
#

I have an implementation question that I'd like some guidance with: I have Characters with a set of abilities, where each character is a prefab, and the character's abilities are also represented as a list of prefabs within the character prefab. My problem is as follows: In the general case, each cast has an individual cooldown, but I'd like for my implementation to handle the case that different casts share a cooldown. Some relevant code snippets:

public struct CastContainer {
  public Cast castPrefab;
  public int cooldown;
  public int timer;
  // ...
}

public class Character {
  public CastContainer[] castContainers;
  // pseudocode regarding cast:
  void FixedUpdate() {
    if (canAndWantToCast(castContainers[i])) {
      Cast(castContainers[i].prefab);
      castContainers[i].timer = castContainers[i].cooldown;
    }
    // ...
  }
}

So, in the general case, each cast handles their own cooldown. However, I want to flexibly handle the case that, in some fashion, I've told my game that if cast0 OR cast1 are casted, I want both to go on cooldown. How might I elegantly write this? I can think of ways off the top of my head, but nothing that doesn't feel hacky 😦

soft shard
# short quiver I have an implementation question that I'd like some guidance with: I have Chara...

One way that comes to mind is firing an event or calling a function that will happen on all casts, that event/func could take a "CooldownType", enum or ID, and if cast0 and cast1 have the same ID or "type" when that event is fired, they can respond with starting their own cooldown - for something like cast2 to not respond in the same way, it would only need a different ID/type than cast0 and cast1 would be using

hexed gulch
#

Hello! I am trying to implement a stepOffset to my controller. I am currently using Modular First Person Controller from JECASE on asset store, but it does not have step offset custo. I would like to continue using this controller as I am pretty deep into development. I cannot add an additional character controller or else my player flys up. I have been at this for the past hour and dont want to resort to slanted planes. Any help appreciated!

void basalt
#

I can draw something if that doesnt make sense

#

and the maybe compare the world height of whatever that raycast hit, with the controller's world height

hexed gulch
#

Thanks! I will work on it more tomorrow and try and implement this into a script!

modern atlas
#
 {
   Vector3 cameraPosition = Camera.main.transform.position;
   Vector3 playerPosition = playerTransform.position;

   float followThreshold = 3.0f;

   float verticalDifference = playerPosition.y - cameraPosition.y;
   if (Mathf.Abs(verticalDifference) > followThreshold)
   {
     // Start following the player smoothly by locking onto their Y position after the threshold is crossed
     float targetY = playerPosition.y;
     cameraPosition.y = Mathf.Lerp(cameraPosition.y, targetY, Time.deltaTime * 5.0f);
     Camera.main.transform.position = new Vector3(cameraPosition.x, cameraPosition.y, cameraPosition.z);
   }
 }```


the slower the player moves upward, the more it jitters. anyone know why it does that?  I tried making it move fast and it doesn't do that, only when it levitates slowly up
cosmic rain
#

Which might or might not be related to the issue.

modern atlas
#

would SmoothDamp work?

cosmic rain
#

Probably. Or just MoveTowards

leaden ice
#

Also why the new vector3 at the end there?

modern atlas
#

I changed it. I used cameraPosition.y and assigned it the MoveTowards function and it somewhat works, just gotta tweak the speed

#

ty btw, Dlich (dont wanna ping lol)

hoary mason
#

Using context steering, how can I make an enemy reach its target behind a wall? Whenever I try it just gets stuck facing at the wall.

Basically I have it set so that the enemy uses a dot vector between the target and each direction and then gives said direction a positive weight. Then it raycasts to each direction to check for obstacles, then if so gives it a negative weight. The substraction from the positive and negative result in the direction to move. Whenever the target is behind a wall the weights on the direction to the target just cancel each other out and the others just stay at 0

grand aurora
#

Hi, guys! I am working on animation for my player and have a question. I am using WASD input to set the proper direction animation. However i think it is better to check the direction movement of the player and set animation in accordance with it. How can i determine player direction using this input?

movementX = Input.GetAxis("Horizontal");
movementZ = Input.GetAxis("Vertical");
mellow sigil
#

2D or 3D? If 2D, top down or sideways? If 3D, first person or third person?

mellow sigil
#

If vertical axis is > 0 then movement is forward, if < 0 it's backward, and horizontal > 0 is right and < 0 is left

worldly hull
#

im creating a scroll rect pagination UI

#

while i was dragging it, lets say im dragging 20th elements

#

if i went to certain threshold, the UI spawned 21-30th elements, somehow my view will jump to 30th

#

like automatically went to the latest(bottom) element

#

how can i prevent that?

knotty sun
#

you using unity ui or uitoolkit?

worldly hull
#

not using any plugins atm

knotty sun
#

uitoolkit is much much easier to use for this kind of stuff

worldly hull
#

but then it was sprawling out of control

#

annnnnnnd we need to fix it or find something better

knotty sun
#

I would really recommend uitoolkit, it's much more flexible and, more importantly, much easier to customize

worldly hull
#

okay

#

i gonna try it first

#

thx πŸ‘

trim schooner
#

1- it's 'etc' not 'ect'
2- this is a code channel and that is not a code question -> delete and ask in #πŸ’»β”ƒunity-talk

celest vault
#

hi, i was wondering how i can include a separate .net project in my assembly-csharp.csproj? unity seems to regenerate the project file and remove my project reference every time.

#

and perhaps more specifically, is there a way to have a custom solution layout? i would like to place my projects in src/ProjectName while still keeping Assets in the root of the solution

knotty sun
celest vault
#

that's not what i'm asking about?

knotty sun
#

that is exactly what you asked

celest vault
#

i mean i'm not here to argue semantics. it's just not what i'm asking.

#

let me know what confuses you and i can clarify

knotty sun
#

this ' how i can include a separate .net project in my assembly-csharp.csproj'

celest vault
#

a project reference is a basic .net functionality

somber nacelle
somber nacelle
knotty sun
#

ah, missing the word reference

celest vault
#

well, i guess how can i include the dll as a reference without it being overwritten

knotty sun
#

put it in a folder called Plugins in your project

somber nacelle
#

if you are not using assembly definitions in your unity project then simply including the dll in the project is enough

celest vault
#

as a .net dev this is a nightmare lmao

somber nacelle
#

yes well hopefully with the switch to the coreclr in the next couple years it will be a more normal process

knotty sun
# celest vault as a .net dev this is a nightmare lmao

personally what I do, is have my source files in folders external to Unity. I create symbolic links into the Unity projects and I use links to them in my .Net solution projects to get them into my solutions for creating dll's, that way I have one code base I can work on both inside and outside Unity

celest vault
#

related-ish, how could i create a modding api (like an IMod interface) that the game can then load? my idea was to let users compile their own project using the modding api as a nuget package and place the resulting dll imply in MyGame_Data/Managed, which i'm hoping is then loaded by mono. i'm just not sure what to do from there.

midnight sun
#

Why does converting to and from json make my actions work, but when I use the commented line nothing happens?

#

This is the new input system btw

#

I'm using XR and both controllers are using different users.

loud igloo
#

yall i need help

#

how do i set up my visual studio cuz it looks weird

knotty sun
#

!ide

tawny elkBOT
loud igloo
#

oh yeah btw im new so can i get help on like how to fix bugs and ask for ideas?

rigid island
loud igloo
#

ok and 2 more questions; what should i start with 2d or 3d, and what can i use for pixel art(for free,im poor)

rigid island
#

both apply the same exact concepts, doesn't change much in those terms. Also there are plenty of free assets, nothing stops you from getting those to start with

#

check places like asset store and kenny

loud igloo
#

yeah but im trying to but a little bit more effort because i know how to acctually draw

rigid island
#

so don't you have an app to draw already?

#

just export it to unity

#

they have plenty of software out there for pixel art

loud igloo
rigid island
#

something like asprite

#

for pixel art

loud igloo
#

0k and the frames for pixel art are just pictures right?

#

like animations

rigid island
#

a series of frames like any moving picture yes

#

Unity has its own Animation tool you just put the frames

loud igloo
#

oh ok so any other things i need to know?

rigid island
#

would suggest you go through the !learn pathways, start with the Essentials it shows you a lot of the tools esp 2D

tawny elkBOT
#

:teacher: Unity Learn β†—

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

rigid island
#

they also have tons of other 2D specific lessons but would do essentials and go from there

loud igloo
#

ok thanks for the info

waxen blade
#

I've recently incorporated object pooling into my game to improve performance, so it's new to me. I need to change the sprite of one of the objects that's currently in the pool while the game is running. If there's a hundred gameobjects, I don't know if it would make sense for me to do a loop to change the sprite of all those game objects (could cause a lag spike?), or if I'm better off just making an entirely new pool with game objects that use the different sprite. Does anyone have suggestions on a best practice for this scenario?

steady moat
waxen blade
# steady moat Just change it when you unqueue one.

I guess I would have to store the new sprite somewhere, and everytime an enqueue occurrs, do an if statement to see if the current sprite matches the new sprite, if it doesn't, change it to the new one?

woeful spire
woeful spire
waxen blade
#

Makes sense, thanks guys.

summer hazel
#

if I'm getting a total editor crash that traces to native Unity C++ code, is my only option to open a bug report? i assume those modules are all closed source

hexed gulch
solemn ember
#

sup gang

#
public async void CreateRoom()
{
    // Check if player is in a lobby already, if so quit it
    RoomFound = false;

    try
    {
        var options = new SessionOptions
        {
            MaxPlayers = 2
        }.WithRelayNetwork();

        var session = await MultiplayerService.Instance.CreateSessionAsync(options);
        RoomFound = true;
        _currentSession = session;
        session.PlayerPropertiesChanged += UpdatePlayerStatus;
        session.CurrentPlayer.SetProperty("PlayerName", new(AuthenticationManager.Instance.PlayerName()));
        session.CurrentPlayer.SetProperty("PlayerReady", new("false"));
        session.CurrentPlayer.SetProperty("LeaderID", new("-1"));
        await session.SaveCurrentPlayerDataAsync();

        LoadAllDecksInList();

        //_hostNameText.text = AuthenticationManager.Instance.PlayerName();
        _lobbyRoomCodeText.text = session.Code;
    }
    catch (SessionException e)
    {
        Debug.Log(e);
    }
}```
#

I have this code to create a lobby, which is an "Async" void

#

so I can use await, try and catch

#

what if, from another script, I call this function

simple egret
#

It'll execute, but you cannot await it from the calling mehod

#

(since it does not return an awaitable type, like Task or Task<T>)

solemn ember
#

😦

#

I'm using the "RoomFound" bool for this, but it's prone to errors

#

see here

simple egret
#

Exceptions will not be bubbled up either (since it's when you await that the runtime checks if the an exception occurred), but you're covered on that since the whole contents of the method is guarded with a try/catch

solemn ember
#

it waits 2.5 seconds and checks for the bool "RoomFound"

#

hmm I see, I guess...

chilly surge
#

If you want the caller to be able to await your CreateRoom, and you want it to tell the caller if the creation was successful, then make it async Task<bool> and return the result.

solemn ember
#

I should make a function here, and call it from my actual CreateRoom()

solemn ember
#

so make this a task

#

that returns a bool

#

and here

#

I could have the await and it will work?

simple egret
#

That method isn't async so you cannot await in there

solemn ember
#

yup, I would have to also make it a task

#

I think

chilly surge
#

Eh, I would not recommend using both async/await and coroutines together. They both (more or less) do the same thing, stick to one or the other.

#

Ideally you'd just use async/await for everything, or coroutines for everything, not both. If you have some foreign code that uses a different mechanism, wrap it into a task/coroutine.

solemn ember
#

LobbyRoomManager.cs

#

MainMenuUIManager.cs

solemn ember
#

but yeah... they're 2 different scripts

simple egret
#

I guess you could do a custom coroutine type that starts an async task and periodically checks whether it's finished, but it's indeed better to stick to one of the two systems exclusively

solemn ember
#

πŸ‘€

#

could I get a ... napkin code as an example of what I should do?

chilly surge
#

Make a decision first, do you want to use tasks or coroutines?

solemn ember
#

I have never used tasks

#

so I don't know

#

whatever you recommend I'll try it

#

I normally use coroutines, a lot

chilly surge
#

Async/await is task.

#

If you decide to stick to coroutines, then turn all your existing code into coroutines, no async/await. If you have foreign code that uses async/await, wrap them into your own coroutines.

solemn ember
#

well I rather keep my Task

solemn ember
chilly surge
#

Then I would recommend use task for everything, including rewriting your existing coroutine code into tasks. Mixing the two will just lead to problems later down the line.

#

Well, it has already led to problems, as the one you are having right now.

solemn ember
#

so I should turn my coroutine into a task

#

I'm down for that

chilly surge
#

If you are going that route, I can recommend UniTask.

solemn ember
#

πŸ‘€

chilly surge
#

You can work on rewriting you existing coroutine code into async/await, and you won't have the problem of mixing the two anymore.

solemn ember
#

that... sigh

#

what do you think of this solution

#

MainMenuUI.cs these will call the tasks from my other script

#

to create or join the task

#

and in my other script, I'm calling the Coroutine

#

which will execute UI stuff there

#

what do you think of that?

chilly surge
#

This is quite a mess, the coroutine in your first script calls an async method in the second script, and then when that method finishes it now has to start a coroutine of the first script

solemn ember
#

no

#

only one coroutine

#

they're void now

#

Void > Task > Coroutine

chilly surge
#

Okay sure, but from my understanding, your first script is where the actual logic lies, your second script is only there to handle the create/join part, and then it should hand the control back to first script.
But because you don't know how to do that, so instead the second script calls some method in the first script after it's done, effectively spliting your main logic into two scripts.

solemn ember
#

πŸ‘€

#

yes

chilly surge
#

Which is my point about not mixing coroutines and tasks, if you use only one of them, the main logic will sit only in the main script, and the part that calls the second script will just await/yield it and continue. The second script will no longer need to even know the first script exists, untangling this mess.

solemn ember
#

πŸ₯΄

#

but I wouldn't know how to do that

#

"Use UniTask"

chilly surge
#

I gave you the decision to "use only coroutines" or "use only tasks" but you still haven't decided yet.

#

Or I guess there's a third option, still using a mix of both.

solemn ember
#

I want to use a task to create the room

#

I assume it's what's best

chilly surge
#

It doesn't really matter which one you choose, but choosing one means you want to write everything in that, and not mixing them.

#

Unless you don't have the time to rewrite existing already mixed code, in that case you can wrap task into a coroutine (or wrap coroutine into a task, depending on the caller)

solemn ember
#

I don't know if I want to use UniTask

#

but I'm down to make my coroutine, a task

#

that way I have both tasks

chilly surge
#

Make your decision:

  • I want to use tasks for everything, and I'll rewrite all my existing coroutines into tasks (you will want to use UniTask for this so your life is easier)
  • I want to use coroutines for everything, and I'll rewrite all my tasks into coroutines.
  • I don't have the time to rewrite and just have to mix the two.
solemn ember
#

btw the coroutine

#

it's just to have some delay on my UI, it looks smoother that way

#

btw

#

I have to download UniTask from github?

#

or I can add it through the package manager

chilly surge
#

Have you decided 1 2 or 3 yet?

solemn ember
#

all tasks

chilly surge
#

Yeah you can add UniTask via package manager, their repo README has instructions.

solemn ember
#

one sec

#

I'll brb in like 5-10

#

what I did work nicely, but I'm willing to improve my code

#

if this is better

#

I'll brb in like 10 minutes tho 😦

blazing tiger
#

Can someone refresh my memory on Gameobject cloning and spawning? I was going to offload some of my code that handles creation of objects into a separate script but remembered you can only instantiate in monobehaviors

#

All it does is basically copy a gameobject, strip everything except for mesh renderers and filters and apply a specific material to them. Ideally it's just a helper method that takes in any gameobject and returns processed one

#

Would this be possible without adding a whole another component to a gameobject?

mellow sigil
#

Instantiate is a static method. You can call UnityEngine.Object.Instantiate anywhere

blazing tiger
#

Wow didn't know the static instantiation thing

#

Lemme try that

solemn ember
lean sail
blazing tiger
#

Sure seems to be working statically, tnx

#

For some reason I thought there was something special about monobehaviors in that regard

soft shard
short quiver
#

My project's prefabs keep getting overwritten by an older state, and I have no idea how. How do I enforce that, at a given moment, the version of the prefabs persisted in the Asset database are the ones that are present in my project?

modern creek
#

I'm just getting my applet stood up (webgl app) and there's a lot of visual tearing and failed antialiasing in the applet (but not in editor or in windows builds). What.. do I need to explore to configure and fix this?

#

(look at the edges of the hexes - left image is the webgl applet)

crude mortar
#

both look equally aliased to me

#

left image:

#

right image:

#

one is just much lower resolution

#

its not really an aliasing problem, more like just seeing a completely different color through the cracks in the ground

#

which will naturally create those small pixel gaps due to monitors being pixel-based and objects in the world being floating-point-based

#

(can't speak to the tearing though, sounds like vsync issues with the engine on that platform and no clue if you can do anything about it)

modern creek
#

sorry, I didn't mean tearing like vsync tearing, I meant the antialiasing

#

it's really bad on the web version.. but it might be a resolution thing .. I just noticed i'm running the editor build in 4k and the web build in 1920x1080 from the canvas size

#

I'm not really sure what the appropriate method is - like.. size the canvas with javascript to the browser size?

#

I'm hunting around for a good webgl template but i'm pretty bad with web stuff

tropic garden
#

Quick question, is there a common reason windowed mode would not include a windows bar at the top of the application? Every time it launches, the bar is there but then after the splash screen it disappears

#

I would like the bar to be there, is there a way to force it? I've tried declaring the fullscreen mode in script, even using a couroutine and key shortcuts to do it manually, and nothing I've attempted has worked. Am I just missing something?

wintry crescent
#

just to make it clear that we're thinking the same thing

swift falcon
#

How do i learn things? Im gettting to a point where I dont know what I dont know how do I learn things? Also whats the best way (or a good way) to refrence a component on a prefab in a script on the same prefab

wintry crescent
lean sail
#

you dont reach a different part of the community by posting in both channels. its just an annoyance to those who look at both

broken heron
#

I have a question, when using Input.GetButtonDown does it always have to be in the update method ?

leaden ice
#

Update, LateUpdate, a coroutine that has a loop that runs every frame, or something called from one of those places.

broken heron
#

ok, I thought so but figured maybe there might be another way.

lean sail
broken heron
#

That's more of what I was looking for, I'd imagine the overhead however small it might be would be better, but then again maybe the new event system is using the same update code something similar to detect.

lean sail
#

the performance of this stuff basically shouldnt even be considered

soft shard
#

How do I change the "Color Over Lifetime" property of a Particle System at runtime? This doesnt seem to change anything, ive also tried changing col.color.gradient directly without the g variable and looping colorKeys to change it, am I missing something?

for (int i = 0; i < vfx.Length; i++)
{
var col = vfx[i].colorOverLifetime;
var g = col.color.gradient; g.colorKeys[0].color = g.colorKeys[1].color = tone; 
col.color = g;
}
leaden ice
soft shard
# leaden ice `vfx[i].colorOverLifetime = col;`

Thats the strange thing with the particle system, you cant assign those properties directly, for example

var main = vfx[i].main; main.startColor = tone;

is all thats needed to set the start color, but doesnt seem to be the same for color over lifetime, if I try vfx[i].main.startColor = anything I get a read-only error, same with vfx[i].colorOverLifetime = anything, same for any of the sub properties like vfx[i].colorOverLifetime.color = ...

#

Now im really confused, creating a new GradientColorKey[] and passing that seems to work, but why would I absolutely have to create a new struct for this? Why cant I just change one value of the existing struct? Doing it this way means if I have 5 color keys, id have to make a new array, loop through all 5 just to change 1 then pass that whole new array, instead of just change the 1 index directly, is this the only way?

echo musk
#

I've got a shader that I want to use to give a 2d sprite a semi-white overlay when the mouse is hovered over

#

The shader will turn my sprite green, red, any other color

#

but when I tell it to turn it White, it does nothing

#

What am I doing wrong?

void basalt
#

detect if your player is trying to climb steps. do the raycast. teleport him to the new position if it succeeds.

#

theres probably some other checks you'll need to do, but that's basically the gist of it

#

you should probably draw lines as well to make sure your raycasts are happening in the right spot

hexed gulch
#

I ended up getting the script to work

broken light
#

why do i get this error:

IndexOutOfRangeException: Index was outside the bounds of the array.
UnityEditor.Editor.get_target () (at <c84e7af800564ed28d201f1f7edf8e24>:0)
WallManagerEditor.OnEnable () (at Assets/Scripts/Walls/Editor/Wall Manager Editor.cs:43)

that is this line of :

private void OnEnable()
{
    _asset = target as WallManager;
}```

i don't see why that would be an error ive made plenty editor scripts in my time and i've never had this issue before.
#

im going to assume it must be an engine bug not something i've done since i dont have access to get_target

broken light
#

this

dusk apex
#

Are you doing some weird multi target selection event from the inspector?

broken light
#

no i only have one scriptable object of it

dusk apex
#

I'm ensuring it isn't some sort of indexer overload

broken light
#

class variable WallManager _asset;

dusk apex
#

Reducing the complexity by removing the assignment and cast from the equation.

broken light
#

no they both print WallManager

#

the editor seems to work even with the error popping up

dusk apex
# broken light no they both print WallManager

So if you do not execute that statement and simply log the two there are no errors? (not caring if it works or not, simply if there is an error being thrown or not) cs private void OnEnable() { Debug.Log($"asset: {_asset}"); Debug.Log($"target : {target}"); Debug.Log($"target as WallManager : {target as WallManager}"); //_asset = target as WallManager; }

broken light
#

it seems to all show wall manager correctly even for _asset when it should technically be null v.odd

#

let me restart unity maybe something has gotten stuck

#

ah restarting fixed it

#

how odd

#

something funky must've gone on when recompiling after editing a script

summer hazel
#

anyone know if there are plans (or maybe already implementations, in Unity 6) for C# 12 features? or are they just not bothering with backporting features now since they're working on porting everything to CoreCLR/.NET 8 anyways?

#

not that there's anything in particular i need, just curious

solid relic
#

I have a placing script that uses a raycast to find a spot to place the object, the problem with this is that where it WILL go is sometimes inside the wall or something (like in the image, the red is me holding down my place button), how do i make it have an offset or something?

dusk apex
solid relic
#

The red card is a clone of the yellow card, so currently it is clipping into my desk, I need it to not clip into the desk

dusk apex
solid relic
dusk apex
solid relic
#

What if the size changes? Like if I have a different object I want to place

dusk apex
summer hazel
#

but what dalphat mentioned is the solution otherwise, just depends on what you have going on

rough fern
#

No idea which channel could be for that, however
I've got a class ClassA and ClassB, the latter taking ClassA for a variable. I've got multiple ClassAs attached to a gameObject, and need to assign a specific one to ClassB in another gameObject, hoepfully through editor.

// Some visualisation of the code
public class ClassA : MonoBehaviour {...}

public class ClassB: MonoBehavior
{
    public ClassA classA;
}

Is that even possible, if so, then how?

rough fern
knotty sun
#

open 2 inspector tabs, lock one to the from object, select the to object, drag and drop the correct classa

rough fern
solid relic
solid relic
summer hazel
# solid relic Yeah that won't work because it can be any rotation

it'd work, you'd just need to rotate the object according to the raycast hit's normal (probably using Transform.LookAt but it depends on your object)
you'll have to do that with either method, more or less - since with dalphat's method you'll need to know which direction to actually offset the object toward, otherwise it'll just go half its size into the surface, probably at the wrong orientation, unless you've already figured that part out

#

(if you want it to be flush with the surface it hits, which I assume you do)

solid relic
summer hazel
#

you shouldn't need to do anything with the collider (unless you're trying to ensure valid placement or something, so that it isn't intersecting with anything). the raycast hit's normal should be be enough, as long as the normals on your mesh aren't a mess i think

#

(at least for the rotation part)

#

if you do try to validate the placement with the collision you'll probably need to offset the placement a tiny bit so they aren't fully touching, or use some method to check how much of the mesh is intersecting with the other one i guess

fringe ridge
#

Any ideas how to get the cell the mouse is touching in a 2d isometric tilemap, that has been rotated to 35.264,45,0 to match a 3d cameras isometric perspective?

fresh hazel
#

Hey I'm calling Destroy on an object when I click on it but when that happen i get the following error: (image)
My issue is that the error itself doesn't seem to come from my code but from the EventSystems
I'm calling Destroy that way:

        public void TryGiveBurger()
        {
            // Update health

            if (_health <= 0f)
            {
                OnDeath();
            }
        }

        protected override void OnDeath()
        {
            CustomerManager.Instance.UnregisterCustomer(gameObject);
            Destroy(gameObject);
        }

Would anyone please know how I can fix that?

leaden ice
#

or is otherwise processing somehow

#

It might help if you do. something like deselect that object before destroying it and/or delay destroying it until the next frame.

fresh hazel
#

Also I tried this EventSystem.current.SetSelectedGameObject(null); but it doesn't do anything

#

My old code was

        protected override void OnDeath()
        {
            CustomerManager.Instance.UnregisterCustomer(gameObject);
            StartCoroutine(Delete());
        }

        private IEnumerator Delete()
        {
            yield return new WaitForEndOfFrame();
            Destroy(gameObject);
        }
leaden ice
#

Yield return null is the way to wait one frame

#

But I might be mistaken about deselecting it being the problem, it might just be because you had moused over it.

fresh hazel
#

hmm i still have the same error

leaden ice
#

Making it block Raycast = false might work better

#

Or Raycast target

#

Forget what it's called

fresh hazel
#

I'm trying that

#

Yup I added GetComponent<Image>().raycastTarget = false; and it works, thanks a lot!

leaden ice
#

Nice

fresh hazel
# leaden ice Nice

Hey it's me again, so apparently it fixes the issue in Unity editor but I made a build and sent it to someone and the error pop up again

vivid heart
#

I am developing an inventory system for an MMORPG and would like to dynamically create objects, even if there are no pre-created ScriptableObjects. I plan to use both random parameters and base parameters for these objects. Additionally, I need the objects to be able to be created on a server request or purchased in a store, with the ability to assign items received from the server. Is this even possible? What efforts and approaches will be required to implement this system? I am considering the possibility of using reflection and flexible OOP approaches.

I would appreciate any advice and ideas!

leaden ice
lean sail
pure grove
#

hello, what I'm doing wrong? When Im moving slider to zero, db goes back to middle

lean sail
boreal jewel
#

my dumbass made a whole script that renders a linerender with the same points as a polygon collider to be able to rotate a laser
instead of a simple sprite + raycast

it took 2 HOURS

#

at least it has width

pure grove
next quiver
#

I have a method that instantiates and fires a bullet every second. In the middle of gameplay, the firerate can be changed by getting upgrades. Its not clear to me how to best get the method to take and use the new fire rate value. Currently I am doing a bit of work around by making a public method of the same name and having it call the private firerate method with ref inputs

boreal jewel
#

the best way would be to make the firerate(of the gun) public, and changing it in the upgrades script when the player gets an upgrade

soft shard
#

Some other approaches that come to mind is using a event in your weapon script, your upgrade menu can fire it if it has a reference to your weapon already, or use a broadcaster/global event if not - or you could make a public property that can be changed and add/subtract it from your fire rate, this way your original firerate can remain private and only affected by the class it exists in, while still accepting modifiers that can also be removed later or possibly saved

boreal jewel
#

I don't think it is necessary to keep the firerate private

soft shard
# boreal jewel nice approach, but if they are unfamiliar with events,they could just make a sep...

This is actually similar to what a public property would do, it acts as a variable but it can also act like a paramless function and do some validation, for example maybe fire rate should never be 10 million

The main reason youd want a variable a class uses like firerate to be private, is cause only that class actually uses the value, everything else might just want to see it, but not modify it directly, when you allow that, then literally any script in your project can modify it at any time, and if thats happening from multiple places, it can be difficult to debug, or run into race conditions where 2 classes are fighting to change the value

boreal jewel
#

alr, I get it

#

thanks

soft shard
#

Np

blazing tiger
#

Are you supposed to create transforms from position and rotation in order to use point transformations? If I wanna transform a point to local space (location+rotation) but it isn't tied to an existing gameobject, what's the best approach?

somber nacelle
#

if you don't have a transform, then what "local space" is this supposed to be converted to?

blazing tiger
#

I'm blabbering let me rephrase it more coherently

#

I have a point and I need to offset it by some position vector and rotate by some quaternion

#

I could do it separately but I'm pretty sure that's what TransformDirection does anyway. Is there any way to do it in one go?

somber nacelle
#

you can rotate a direction vector by multiplying it by a Quaternion representing the amount of rotation so just do that and add the offset

blazing tiger
#

I'm doing it rn but it was kinda a hassle to provide both location and rotation for 2 objects in a function, was wondering whether there's some transform data type that combines both of these

#

And maybe scale too

#

Like a general purpose transform matrix or something

spare dome
blazing tiger
#

Because iirc transform component also handles things like inheritance, children etc

blazing tiger
somber nacelle
blazing tiger
#

Ty

vivid heart
warped dawn
#

Hey crew. I'm getting a Unity error NullReferenceException: Object reference not set to an instance of an object UnityEditor.Android.AndroidDeploymentTargetsExtension.StartApplication however the APK is uploaded to my device and I can start it successfully. I tried all the solutions I found online but none of those applied to my situation. Anyone seen this before?

knotty sun
#

this is probably the most common runtime error. look at the complete stack trace

wind ridge
#

messing around with a little voxel project, and i'm not sure how i can fix my normals. each voxel is part of the one gameobject, created through vertex/triangle manipulation. currently, the individual cubes have the same shading as the whole object should combined. not looking for code, just a list of things to look into, any help would be much appreciated <3

raven storm
#

Is there anyway to use C#10+ (a version above C#9) with Unity ?

somber nacelle
#

have you googled it? also you will only get the syntax sugar features from c# 10, you won't be able to use anything that is not supported by unity's .net version

raven storm
#

Does flat namespaces count as sugar?

somber nacelle
#

no

rigid island
somber nacelle
#

file scoped namespaces

rigid island
#

ahh ok

#

yea wish we had that at least 😦

chilly surge
#

You would also need to manually patch the compiler binary in your Unity editor installation

#

Not really worth the effort imo.

solid relic
# wind ridge messing around with a little voxel project, and i'm not sure how i can fix my no...

There is a tutorial on YouTube (HERE) that might be beneficial to what you are asking

JOIN THE DISCORD SERVER!

https://discord.gg/aZgBgC2


NOTE: I have NO idea what happened around the 6:30 minute mark with the epilepsy-inducing flashing red screen. Sorry about that :-/

This is my first attempt at a coding tutorial video. As I explain in the vi...

β–Ά Play video
#

It is a series so there will be textures in later videos on it

wind ridge
solid relic
short quiver
#

Can anybody recommend a method of applying and deactivating redundant status effects when effects are applied with a component pattern? For example, suppose I have a state in which a character is made to be drunk for a period of time. What I've seen in the pattern is the following:

public class Drink: Effect {
  private IGetsDrunk Drinker;
  private int timer = 60;

  public void Activate(Target t) {
    if (IGetsDrunk _drinker) {
      Drinker = drinker;
      Drinker.Drunk = true;
    }
  }
  
  public void Deactivate() {
    Drinker.Drunk = false;
  }

  public void FixedUpdate() {timer--;}
}

This solution is pretty nice to me, because the state update is calculated once, and the only calculation to do for the rest of the lifespan is decrease the timer and undo the effect when it's done. This doesn't seem to work if the effect is applied redundantly. For example, if the character drinks a drink at t=0, they can expect to be sober at t=60. If they drink again at t=55, they'd expect to be sober at t=115 (let's say), but the above implementation would make them still sober at t=60. Is there a clean way to account for this in a component pattern?

chrome trail
#

I'm trying to get what the camera sees (the first image) to map onto a raw image in a canvas (the second image) but doing so causes the second image to be stretched out and kind of low res. How do I fix this?

rocky vale
#

Hi I'm trying to make an animation script. I made the clip. I'm familier with python but not so much C#. I have 2 characters talking to each other with dialogue (text file containing each line of dialogue). The audio comes through, but I need the characters' jaw to be open while it's their turn to speak, and close when not supposed to be speaking. I wrote this script here, Unity found no errors, but will it do what I actually want it to do?

#

speaker should match the name of the character object

quartz folio
# rocky vale Hi I'm trying to make an animation script. I made the clip. I'm familier with py...
  1. start is never going to be called, as it's not capitalized how Unity will expect.
  2. I have no idea where you call ProcessScript
  3. Your File.ReadAllLines won't work in a build, and will only work in the editor because the file system is completely different when built (Assets doesn't exist).
  4. Do you have error highlighting in VS Code? While it looks highlighted, I'm suspicious it's unconfigured
rocky vale
#

I did take part of this from someone else's code

#

That's in Main.cs whcih controls the whole thing

#

But it didn't actually do anything

quartz folio
#

Also this is invalid:

rocky vale
#

Yeah I'm just throwing stuff at the wall to see what sticks πŸ˜…

#

I did do C# research but perhaps not enough

quartz folio
#

well, read and understand the dot points I've mentioned for a start

#

if your IDE isn't configured (4) then that's a major thing you need to set up asap

rocky vale
#

It might not be configured

quartz folio
#

!vscode

tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

rocky vale
#

Hmmm perhaps this is important

#

(Sarcasm, yes I know the SDK is required)

solid relic
#

How would I create an inputmanager for keybinds?
I'm thinking something like this:

public InputManager instance;
public List<keyBind> keyBinds;

private void Awake(){
   if(instance == null)
      instance = this;
   else
      Destroy(gameObject);
}

[System.Serializable]
public struct keyBind
{
    public string name;
    public KeyCode key;
    public KeyCode altKey;
}

And then in my player script it would look like:

if(InputManager.instance.keyBinds[0].key || InputManager.instance.keyBinds[0].altKey){
   // Jump code
}
cosmic rain
solid relic
cosmic rain
solid relic
#

Why would a dictionary be better?

cosmic rain
# solid relic Why would a dictionary be better?

It would be faster to get the value compared to a list. Though, if you just indexes as in your example, a list would be around as fast. But then you have an issue of poorly readable code, where you hardcode the indices.

solid relic
#

How do I access items in the dictionary? I haven't really used dictionaries

wind locust
#

Hey all, is there any tutorials around that go through how to implement text chats with vivox's current version? the documentation is pretty sparse

cosmic rain
native shoal
#

So I'm making a rope with IKs, but I'm trying to add gravity. Heres my current idea:

Calculate the ik as normal, then I'll find the middle segment, and move it down. after that, i'll calculate the other to halves back from the center with the anchor thing. I'm trying to figure out how to code it, but I'm wondering if anyone has any other ideas.

muted schooner
#

I move a pool of objects each fixed update, but since they are marshalled, it ends up with some performance loss. Is there a workaround to keep the transform in memory?

#

should I just store it as a variable, is it fine?

maiden fractal
solid relic
# cosmic rain Check the C# docs.

Currently i've got this:

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

public class InputManager : MonoBehaviour
{
    [SerializeField]
    public Dictionary<string, keyBind> _keyBinds = new Dictionary<string, keyBind>();

    //public List<keyBind> keyBinds;

    private void Start()
    {
        keyBind k = new keyBind();
        k.key = KeyCode.W;
        k.Altkey = KeyCode.UpArrow;
        _keyBinds.Add("Forward", k);
    }
    [System.Serializable]
    public struct keyBind
    {
        public string name;
        public KeyCode key;
        public KeyCode Altkey;
    }
}
cosmic rain
maiden fractal
#

I guess, just wanted to make sure they don't use a mesh with no way to shade flat which is quite likely here

cosmic rain
#

Even with just 8 vertices

maiden fractal
# cosmic rain Even with just 8 vertices

It is possible with partial derivatives of the position for example but I think they still usually use 24. Some also do that to split the chunks into different directions to cull the ones pointing away from the camera

#

also if greedy meshing is implemented, the vertice count increase isn't that big of a deal

cosmic rain
maiden fractal
#

Again you can work around that too

sonic swan
#

I've been stuck on this for hours but how would you go about creating a rope that player can climb and swing on which uses physics. For a 2d project btw

sonic swan
#

Making the ropes isn't the problem .

#

The ability to latch onto it and generate momentum and climb is

leaden ice
#

That's what you asked...

leaden ice
sonic swan
#

I will have a look

#

Hingejoint2d right

solid relic
cosmic rain
#

Input.GetKey(keyDictionary[keyKey])

solid relic
#

And then there is Input.GetAxisRaw("Horizontal"); would i just use

float horizontal = 0;
if(Input.GetKey(keyDictionary[left]) {
   horizontal = 1;
}
lean sail
solid relic
cobalt bloom
#

I generate a mesh for my voxel grid, and I make sure to never repeat vertices. However, this makes the lighting off, as the vertices never repeat and so, faces reuse older vertices. This makes the faces render in a similar fashion to balls, which could look nice if the voxels were very small, but it looks off when the camera is close to the voxels.

#

How can I fix this issue?

cosmic rain
cobalt bloom
cosmic rain
#

Well, the screenshot points out otherwise.

cosmic rain
#

You wouldn't see here whether the triangles share vertices or not.

cobalt bloom
# cosmic rain You wouldn't see here whether the triangles share vertices or not.

They do share vertices because I wrote the mesh generation myself so I know what it does. I basically create a list of each face that would be visible (no voxel is occluding it), and then when I cut the face into vertices and triangles, I check if the vertice is unique or not. If its not unique, I use the index of the vertice that already exists in that position.

cobalt bloom
#

Is there a way to keep the same optimization while having the normals correct? I know the normals look like the voxels are balls due to the vertice sharing.

cosmic rain
#

Your triangles need not to share vertices to get flat shading.

cosmic rain
#

You can patch this in a custom shader by calculating the normals for each pixel, but that would be even more expensive

cobalt bloom
#

;(

#

I used a similar optimization in a voxel engine I made outside of Unity a while ago and I remember using screen-space normals there too.. I suppose there's no way out of that then?

cosmic rain
#

There isn't. And screen space normals are probably gonna be way more expensive than some extra vertices.

cobalt bloom
#

I guess I'll just keep the vertice unique thing in the trash bin until I find some way to make it useful

#

Thanks!

cosmic rain
#

And to be honest, if you're aiming for a performant engine that can render a huge amount of voxels, unity is probably not a great choice.

cobalt bloom
#

Thanks for the help. Next I plan to implement greedy meshing to reduce vertice count.

stone pewter
#

unity's fine for this kind of thing too, you'll just need to use some of the more low level APIs imo!

stone pewter
cobalt bloom
stone pewter
#

oh, hm, which render pipeline are you on?

#

if it's URP/HDRP then you'll prolly want to use shadergraph

cobalt bloom
#

rn I'm on the default one but if I can use ShaderGraph for this sort of thing then I should probably use it before trying to delve straight into anything too complex

stone pewter
#

I forget if SG has support for the built in RP

#

(I mostly write shaders in the built in RP)

cobalt bloom
#

I believe ShaderGraph should support the built in RP as it doesn't say its for URP but says URP provides support for it

#

but a quick google search says otherwise

#

so I guess not

stone pewter
#

I think it was added in 2021.2?

#

anyway, you'll want to do something like this:

outputNormal = normalize( cross( ddx(worldPos), ddy(worldPos) ) );
#

assuming the outputNormal is in world space, it might not be

cobalt bloom
#

How do I create a shader in the built in RP? I want to check if it'd be comfortable or not before going with Shader Graph

stone pewter
#

do you want to support lighting?

#

if so then SG is going to make life a lot easier

#

(unity has kind of started discouraging writing shaders by hand through their design ever since shader graph)

#

(writing shaders by hand has a ton of drawbacks if you want to support all the features like lighting, motion vectors, scene view selection, all that. but you get a lot of control!)

#

basically using SG is more future proof lol

cobalt bloom
#

I suppose I don't really need a ton of control for this project anyway, so SG should work.

stone pewter
#

but yeah right click in project view, Create > Shader >, and then Unlit is writing by hand. shader graph should be similar but I forget, I rarely use it henlo

#

might need a package or something

cobalt bloom
#

I used SG before a little so I should be fine

#

hopefully

cobalt bloom
#

Greedy meshing not going very well at the moment ;-;

#

Can someone more experienced explain to me why my algorithm doesn't work? I basically have a list of every voxel face (that is going to be rendered), and I group the faces if they have the same normal. Afterwards, I iterate over them and check which ones align along the X or Y axes, and merge them if they do.

#

I also check if the distance between them is too much

#

I think I should try to rewrite it fully since this approach is probably wrong

pearl burrow
#

Hi again everyone!

I have a "skill tree" with each skill its script (ItemSkill). The gameobject of the skill contains also the panel that will show when clicked that allow you to upgrade to the next level, and this is for every skill. Since the "price" for the next level will always be the same the initialization of the upgrade panel is made only once at the start.
Wouldnt be better to unlink the upgrade panel from the skills and initialize the panel every time i click on the skills? (so before if i have 10 skills i have 10 panels, now i have 10 skills and one panel)

cobalt bloom
#

I'm guessing not exactly since it looks weird

#

using view space instead of world space makes it look a little better but its still weird

stone pewter
#

there might be a setting to change the output normal space

#

if so, change it to world

wind ridge
stone pewter
#

(there are ways to work around it but that requires specialized shaders)

knotty sun
wind locust
#

i'll move it, cheers

stone pewter
#

uuuh did it get disabled somehow

cobalt bloom
stone pewter
#

yeah that looks disabled

cobalt bloom
#

The way I changed it to a world space normal is by deleting that part and then replacing it with the world space normal