#archived-code-general

1 messages ยท Page 143 of 1

ashen yoke
#

but by creating custom one you can serialize it however you want

dusky lake
idle flax
#

Thanks, that works.

ashen yoke
#

how did you feed it into serializer?

idle flax
#

I have a GameData class that gets serialized, which stores a reference to the Vector3

ashen yoke
#

i mean you extended JsonConverter<Vector3> and then it just works?

#

no extra steps?

potent sleet
#

is JSON.net not able to serialize v3 out the box?

#

could've sworn it did

ashen yoke
#

look above

idle flax
#

I had to add this serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;, but yeah.

potent sleet
#

ahh

potent sleet
#

i remmeber this

normal hedge
#

I am having issue with Singletons - I followed https://gamedevbeginner.com/singletons-in-unity-the-right-way/
The issue right now is the starting Instance, am I supposed to just slap it onto an empty?
Doing that would work for that one scene, but I need the Singleton in at least one other Scene.
Putting the Singleton into DontDestroyOnLoad needs a point where I initially create it, which does not exist currently - and would fuck around again with static references.
The singleton holds the data needed for perks and status effects.

Any suggestions on what to do?

Learn the pros & cons of using singletons in Unity, and decide for yourself if they can help you to develop your game more easily.

rugged goblet
#

I assume your game must have a starting scene? You just instantiate your singletons in that scene and mark them as don't destroy before doing anything else

#

If your other stuff is referencing it statically, you use FindObjectOfType instead of a static reference

normal hedge
#

...Time to create a starting scene then.

#

Thank you

rugged goblet
#

Every game needs a menu scene, gotta have one anyway, no reason to build your game around the assumption that there won't be a scene

glossy granite
#

hey anybody knows how to change parameters at runtime for posteffect volumes for URP?

potent sleet
ashen yoke
#

when you press play

glossy granite
# potent sleet depends which ones sometimes is worth more to make a new profile and fade weight...

just want a red vignette when getting hit
tried using this but it wont work , maybe you approach is easier

 public static void ChangeVignetteTo(Color newColor)
    {
        Volume volume = FindObjectOfType<Volume>();
        if (volume != null && volume.profile.TryGet(out UnityEngine.Rendering.Universal.Vignette vignette))
        {
            instance.m_Vignette = vignette;
        }
        if (instance != null && instance.m_Vignette != null)
        {
            instance.m_Vignette.active = true;
            instance.m_Vignette.color.Override(newColor);
            // volume = PostProcessManager.instance.QuickVolume(0, 
100f, instance.m_Vignette);
            instance.Invoke(nameof(ChangeVignetteToBlack), 1);
        }
        else
        {
            Debug.LogError("Instance or Vignette is not set!");
        }
    }```
normal hedge
#

I think its better to get the start scene out of the way now - while I have a reason not to procrastinate on that

potent sleet
#

just make a separate profile/volume just for the hits and fade the weight in

#

all this extra is useless imo

glossy granite
#

I agree but I have a profile for the night and for the day I guess I will swap depending on the time

potent sleet
#

you're not swapping anything

#

you layer it ontop

#

give it a higher priority and it will overlay night/day profiles just for hits

glossy granite
#

love it thank you so much @potent sleet

loud flume
#

I've been working on a dungeon generator and am now working on visualizing it in game the way I've been doing so seems to me like its very inefficient. The dungeon is a grid and each cell in the grid has a few bools that store if its part of a room or a hallway, a door or a wall, ect. and the way it currently works for rooms for example it checks if a node is part of a room then gets that nodes neighbors and if say the neighbor above is not part of the room and the one bellow is it makes a wall. but it feel like doing this for every node is slow especially since it like a 200x200 grid.

#
 if (point.isCorner)
                    {
                        rotation = 75;

                        spriteToSetTile = sprites[floor].wallCornners_1[Random.Range(0, sprites[floor].wallCornners_1.Length)]; ;

                        if (neighbors[1].partOfRoom && !neighbors[1].halway && neighbors[3].partOfRoom && !neighbors[3].halway)
                        {
                            rotation = 90;
                        }
                        if (neighbors[1].partOfRoom && !neighbors[1].halway && neighbors[2].partOfRoom && !neighbors[2].halway)
                        {
                            rotation = 0;
                        }
                        if (neighbors[0].partOfRoom && !neighbors[0].halway && neighbors[2].partOfRoom && !neighbors[2].halway)
                        {
                            rotation = -90;
                        }
                        if (neighbors[0].partOfRoom && !neighbors[0].halway && neighbors[3].partOfRoom && !neighbors[3].halway)
                        {
                            rotation = 180;
                        }
                    }
grim kiln
loud flume
grim kiln
#

The Stopwatch class, that is not a physical stopwatch.

strange gust
#

idk how advanced this is but i wanted to know if its possible to have a the head of a rig look in the same direction the camera is looking?

potent sleet
ashen yoke
#

just making it rotate is not advanced

#

making it look good is painful

potent sleet
#

if you have a rig it's even easier , with Animation Rigging package with IK

#

but you can do it ofc with anything like LookAt or LookRotation or /we

primal wind
#

If you rotate it manually make sure you clamp rotations unless you want your character to break it's neck everytime you look to far up, down or else

frozen heath
#

Has anyone else had issues with the editor not deserializing their serializedproperties? I recently deleted all the asmdefs in my project and now the serializedproperties show as blank, although the data still exists in the .asset file

ashen yoke
#

guid matches?

#

monoscript asset/ ref guid

#

theres also "type" of reference

#

0-3 i think

#

when i bumped into something similar i ran string replacement on metas to fix similar issues

ionic socket
#

Is there a way to get the enumerable that a transform returns and then do a linq statement on it? ie we can do foreach(transform chil in transform) but I can't do transform.Where(...). is there a simple way to do this?

steady moat
ionic socket
#

the use in the foreach implies that there's an implicit cast predefined, so i'm surprised it doesn't work implicitly with Linq.

steady moat
#

Yeah, not sure why also.

ionic socket
#

alas, it doesn't play ๐Ÿ˜ฆ

gray mural
#

that's strange for me

somber nacelle
#

it's not inheriting from IEnumerable since you don't inherit an interface, you implement it. interfaces are not inheritance.

leaden ice
leaden solstice
ionic socket
#

.Cast<IEnumerable<Transform>>()?

leaden solstice
#

It is shame that it does not implement IEnumerable<Transform>. You should be able to workaround with Cast

leaden solstice
ionic socket
#

casting Transform... back to Transform?

leaden solstice
#

Cast is part of linq and should take element type

#

It casts elements of collection

ionic socket
#

ah

#

that's nice

#

that works on any IEnumerator?

leaden solstice
#

IEnumerable

#

Enumerator is different

ionic socket
#

IEnumerable yeah whoops.

gray mural
#

IEnumerable is "collection"

#

List is also IEnumerable

ionic socket
#

you ever work on something for like, 20 hours, and the final product is like 35 lines, and you feel like, damn.

dusk apex
#

If you're lacking knowledge to solve the problem, you'd study this during the brainstorm phase.

#

"a few days" is a large leeway - take however less time you're needing but be near certain you can solve the problem to be productive. Exposure to creating more games can only help you - you'll be repeating a lot of behavioral practices.

gray mural
#

and it's probably almost nothing in 80% situations

#

and I think that I'm really so slow

#

because I am also interapted too easily

#

dunno why I do say it though

west elk
#

Hi! I'm trying to check that, if given an array of materials (items in crafting slots) there's a match with a predefined array of materials (recipe). I tried with this code but it's always null even if I know that the arrays match, and the Debug.Log just logs the first element of the recipe. Any input?

leaden ice
#

show the definition

west elk
potent sleet
#

I would def use SO for this usecase

gray mural
#

@eager yacht
Sorry for ping, I just wanted to say you that I have solved that issue with textComponents and thought that you may be interested in what was wrong.
After debugging both your and my scripts, I have realised that TMPro is just done badly and has some issues that it shouldn't have. So it was "randomly" making more lines than needed and also changed TMP_Text's rendered height to ~2100 even when not needed. Probably that's not possible to change without doing smth in built-in classes, also that's not the best idea with my level of knowledge unless I wanna waste my time even more.
So I have just made it to change textComponent when its rendered height is changed (with prevHeight) and when its width is set to maximum (max is e.g. 950 and current width is e.g. 939 so that it cannot add one more character, cuz its width is too big (> 11 in our case)).

https://www.nombin.dev/qfxbenleeg
That's a part, where textComponent is changed by assigning text (you have seen it already). I have a lot more to do though, that's not very interesting to struggle with TMP_Text.
I think I should also catch input with new Input System, cuz it's more efficient. Thank you for your help one more time!

west elk
potent sleet
#

oh lol then idk why even use the enums array to make recipes instead of array of SO lol

#

๐Ÿคท

west elk
#

I do have Items SO that I could use instead of the enum but i figured I wouldnt need all the info data, just what item it is

potent sleet
#

eg I typically do it this way

west elk
#

Thing is my materials are not just materials and have more data the it isn't used in the recipe

potent sleet
#
 void CheckAllIngredients()
    {
        if (CurrentIngredientsAdded.Count != RecipeIngredients.Count) return;

        if(CurrentIngredientsAdded.Count> 0)
        {
            bool same = CurrentIngredientsAdded.ToHashSet().SetEquals(RecipeIngredients);

            if (same)
            {
                Debug.Log("Make output");
                MakeOutput();
                Clear();
                StartCoroutine(TimedRefresh());
            }
            else
            {
                Debug.Log("Not Yet Completed");
            }
        }
        
    }```
west elk
#

I will try another approach tho

potent sleet
#

I've done it a while ago it could prob be better

#

but it works

west elk
gloomy stirrup
#

why am I getting this error in my admob rewarded ad script "Assets\New Folder\RewardedAdButton.cs(3,23): error CS0234: The type or namespace name 'RewardedAd' does not exist in the namespace 'GoogleMobileAds' (are you missing an assembly reference?)"... I am using
I am using unity 2021.2.24f1 and admob package version 8.3.0

#

here is the script...

#

using UnityEngine;
using UnityEngine.Advertisements;
using GoogleMobileAds.RewardedAd;

public class RewardedAdButton : MonoBehaviour
{
private RewardBasedVideoAd rewardedAd;
private const string AD_UNIT_ID = "YOUR_AD_UNIT_ID";

public void Start()
{
    rewardedAd = RewardBasedVideoAd.Instance;
    rewardedAd.OnAdLoaded += HandleAdLoaded;
    rewardedAd.OnAdFailedToLoad += HandleAdFailedToLoad;
}

public void OnButtonClick()
{
    if (rewardedAd.IsLoaded())
    {
        rewardedAd.Show(AD_UNIT_ID);
    }
}

private void HandleAdLoaded()
{
    Debug.Log("Ad loaded");
}

private void HandleAdFailedToLoad(string error)
{
    Debug.Log("Ad failed to load: " + error);
}

}

#

Anyone can help ?

simple egret
#

Error on line 3, RewardedAd does not exist inside of GoogleMobileAds.
Examples online show using GoogleMobileAds.Api, did you mean to use that?

tawny elkBOT
#
Posting code

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

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

brisk reef
#

@gloomy stirrup

gloomy stirrup
brisk reef
#

read the posting code

gloomy stirrup
#

ok

simple egret
#

I wrote the solution

#

You replied "yes", did you make the changes?

gloomy stirrup
#

nope doesnt work

#

its not being used even

#

in the code

simple egret
#

Let's do this one differently

gloomy stirrup
#

all I have to do is using GoogleMobileAds.RewardedAd; ... but for that I dont know how to set up assemblies

gloomy stirrup
simple egret
#

Remove the using that errors, entirely

gloomy stirrup
#

ok

simple egret
#

Let's use your code editor's features to fix the errors

gloomy stirrup
#

but RewardBasedVideoAd lies in GoogleMobileAds.RewardedAd; so now its showing error

simple egret
#

Yeah, now that you have the error underlined on RewardBasedVideoAd, hover over the error and click the light bulb icon that appears

#

It'll give you some suggestions, with hopefully one that says "using ...."

gloomy stirrup
#

there are multiple sloution as always

#

which one tto choose

simple egret
#

The one that says "using [something]"

gloomy stirrup
#

there is only generate type and encapsulated feild

#

no using

simple egret
#

Yeah so RewardBasedVideoAd doesn't exist

#

I can't seem to find it on their docs, is the tutorial you're using up to date?

#

I can only find RewardedAd

simple egret
#

Yeah that's clearly not the right way to code, asking an AI

gloomy stirrup
simple egret
#

The official ones from Google

gloomy stirrup
#

beccause I tried on YT but got things that doenst work

gloomy stirrup
gloomy stirrup
#

why error there ?

#

if I remove ; then it will show that ; is expected

simple egret
#

Take inspiration on the syntax of line 128

#

You're missing the lambda expression symbol =>

gloomy stirrup
#

it worked thanks

#

well wich method i have to call from button

#

LoadRewardedAd() ?

swift comet
#

I guess you would know best? We dont know what code does.

gloomy stirrup
swift comet
#

Ah just realised theres a history of chat here, my bad.

gloomy stirrup
#

not a big problem

#

as I am just learning how to do it for my real game

#

but still something to be resolved

mossy snow
#

those are in the editor, so not real ads. Test on an actual device before you assume that

gloomy stirrup
#

THANK YOU ALL it worked.. and now I finally know how to do it

old haven
#

PlayerController(PlayerNetwork):https://gdl.space/yiqulehopa.cs
i want my gun to rotate with me normaly. but it is far away from me and thw rong way after starting the game. In the Player PreFab the gun is normaly placed
pls (im beginner so)

wet shadow
#
public class Bullet : MonoBehaviour
{
    public float speed = 20f;
    public Rigidbody2D rb2d;
    public AudioSource sound;

    void Start()
    {
        sound.Play();
        rb2d.velocity = transform.right * speed;
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

how can i make it so that the bullet moves based on the direction of the transform

#

the rb2d is the firepoint

#

and even though it flips when the character when i go left the bullet still fires to the right

leaden ice
#

rb2d is definitely not the fire point

#

It's the bullet's Rigidbody2D

#

You'd have to show how you spawn the bullet

#

Short answer is make sure the bullet is oriented properly when you spawn it

wet shadow
#
 void Shoot()
    {
        newProjectile = Instantiate(bulletPrefab,firePoint.position,firePoint.rotation);
    }

leaden ice
#

Looks good, guess your fire point isn't actually rotating

wet shadow
#

seems like it

#

when i fire to the left

#

the bullet still goes to the right

leaden ice
#

I know

wet shadow
#

and it pushes me far

leaden ice
#

You're probably rotating your character with the sprite render flipX thing

wet shadow
#

heres how i flip my character

#

Comes from PlayerController

void flip() {
        if(facingRight && inputHoriz < 0f || !facingRight && inputHoriz > 0f) {    
        facingRight = !facingRight;
        Vector3 localScale = transform.localScale;
        localScale.x *= -1f;
        transform.localScale = localScale;
        }

    }
leaden ice
#

I'd guess that the fire point is not a child of the object that is flipping then

leaden ice
wet shadow
#

X

leaden ice
#

should work then

leaden ice
wet shadow
#

it does

wet shadow
leaden ice
#

well you should fix that

#

it's probably just bouncing off the character

pale bay
#

I have a scriptable object that stores a list an object called ShopItem which contains these attributes:

  • string name
  • int cost
  • sprite icon

If the name is the same as the icons file name, would it be better to just do resources.load or is that too resource intesive?
For reference I have 50 items to go through

wet shadow
#

forgot to mention

#

the codes i provided came from different scripts

leaden ice
wet shadow
#

im talking abt the movement of the bullet

leaden ice
pale bay
#

So I intend to have a scroll view with a series of buttons lets say 50 of them. I want to load the data for each button which will display its name (label), cost (int), and icon (sprite). I intend to loop through a scriptable object when I load that scoll view which will contain a list of those objects (ShopItem contains name, cost, and sprite). I can either keep the sprite attribute in that scriptable object and load it when I loop through the scriptableobject and pull it to use it as an icon for that button OR use the name of that index and do resource.load for that sprite instead

#

Im thinking resource.load is resource intesive if I have to load like 50 different sprites at once so im asking here to double check

wet shadow
#

@leaden ice

rb2d.velocity = transform.right * speed;

how can i change this so that it doesnt just travel "right"?

rain minnow
#

Insert any direction in place of transform.right . . .

wet shadow
#

what i mean is

#

@rain minnow make the bullet move to the direction that the character is facing i mean

#

like if the character faces left

#

the bullet should fire to the left not the right

#

that's what i mean

swift comet
#

transform.forward (I think)

potent sleet
swift comet
#

Oh its 2D

potent sleet
#

Instead of flipping the sprite only, you rotate 180 on Y it always faces transform.right

wet shadow
#

it fixed the issue

#

thank you

cedar mist
#

I need help with an issue. I created a trigger that loads in a scene async additively but the scene loads multiple times creating duplicates, how do i stop this from happening?

lean sail
cedar mist
lean sail
cedar mist
#

K ill try it tomorrow when i go on my pc

rain minnow
soft ruin
#

Mathf.Atan weird rounding to -90.0f

whole steeple
#

Hi everyone. I feel like I am missing something really basic, but I need to add a force to a 2D object. This is the code I am using, but no force is added to the object and unfortunately I don't get any errors to guide me where to look. I did try to Debug.Log the enrb and it returns the name of the GameObject followed by 'UnityEngine.Rigidbody2D' which leads me to believe maybe I'm going the wrong way around the AddForce thing...
public void OnTriggerEnter2D(Collider2D collision) { GameObject otherObject = collision.gameObject; Rigidbody2D enrb = otherObject.GetComponent<Rigidbody2D>(); enrb.AddForce(new Vector2(50f, 0), ForceMode2D.Impulse); }

pale bay
dusk apex
#

The purpose of logging here is to see if the function is occurring.

whole steeple
#

Oh yeah, I removed it so you could see only the relevant code. The logging fired as expected

quick elbow
#

Anyone have any thoughts on the free kinematic character controller on the asset store vs using the Unity character controller and writing your own movement code? I'm curious how the kinematic controller on the asset store compares since it is totally independent of the CharacterController component

oblique spoke
quick elbow
#

Yeah, I've already been looking at it and through the code as well. It's an interesting approach to character movement. I'm just curious if anyone has ever benchmarked both and compared, or if there are any thoughts on the flexibility of each?

wide fiber
#
 void PadROtate2()
    {
        Vector3 rotationInput = new Vector3(p_input.rotationAxisX, 0f, p_input.rotationAxisY);
        Quaternion targetRotation = Quaternion.LookRotation(rotationInput);
        Quaternion deltaRotation = Quaternion.RotateTowards(rb.rotation, targetRotation, rotationSpeedForPad * Time.fixedDeltaTime);
        rb.MoveRotation(deltaRotation);

    }```

Guys sorry i dont understand. my character resets back to its original rotation position after i rotate my character using my stick? why? i just want my character to move according to where my stick got pushed ๐Ÿ˜ฆ
quartz folio
#

if the input is 0, then the target is 0

mystic fox
surreal blaze
#

Hello I been trying to create an ability class that o can create abilities with. The ability class works as I am able to do things with it (Call animator triggers, change the gravity of my player. Instantiate objects) however I have a part which I want to apply and x velocity to the rigid body. I can see in the inspector that the player is receiving the velocity as it updates there but the position does not move at all. I do Al my player movement in another script so I worry that may be the cause of my issue. Any ideas on how I can get the dash to work?

fast moon
#

how do u apply that velocity?

#

any errors?

surreal blaze
#

No errors

#

Just a rigidbody.add velocity

#

I see the velocity being updated in the inspector for the duration of the ability

#

But the player dosent move

gaunt wren
#

Currently implementing Instance Pooling into my project, what's the best way to tackle the system?
I'm leaning towards either a Master One that handles all the pools across a scene or an Object Specific one that looks after the pools for a singular object (All the objects that are instantiated by a player for example).

wide fiber
quartz folio
#

Again, you're moving to targetRotation, which is entirely based on your current input values

halcyon venture
#

how can i add to the z coordinate of a 3d object inside the update method so its always moving upward?

#

something like

void Update() {
//in here the z coordinate goes up by one 
}
gaunt wren
#

transform.position+=transform.forward;

halcyon venture
#

ok

#

also would this work transform.position += new Vector3(1 * Time.deltaTime, 0, 0);

#

but change it to z axis

gaunt wren
#

pretty much

halcyon venture
#

ok

#

thanks

quartz folio
#

To be clear, Z is forward

gaunt wren
#

transform.position+=transform.forward*time.deltatime;

quartz folio
#

Up in Unity is the Y axis

halcyon venture
#

i got it working ๐Ÿ™‚

wide fiber
rose dragon
#

How should I write this string format so it looks like a 00:00:00 timer

quartz folio
#

No need for string.Format

rose dragon
#

Seems to work, thanks

gaunt wren
#

is that the rigidbody.add velocity you mentioned or is that the ability?

ionic socket
#

I'm getting a transient missing reference exception when I start my project; within a simple foreach(Transform t in transform). It only sometimes occurs, and the object which is missing (UI_Hand) is never cloned or destroyed in my project. This is also happening on the first iteration, and it's just the t that's unset. It seems to operate most consistently when it's the first time I've hit play after loading unity; or after a full reload.

Has anyone heard of this happening or know why it does? UI_Hand is a plain gameObject that sits in my hierarchy.

quartz folio
ionic socket
quartz folio
#

Unless transform is declared as UI_Hand transform, it's not.

ionic socket
#

er, it's the transform of the gameObject - the built-in unity reference.

#

This error also only happens sometimes, not every time.

quartz folio
ionic socket
#

even if I comment out those lines; the simple Debug.log(transform) is throwing the Object has been destroyed - not even a null result.

#

the Debug in Start() works however.

quartz folio
#

Then OnSetActivePlayer is being called even when your Component is destroyed, how are you calling that function?

ionic socket
#

It's connected to an event. But there's no code that destroys the component or GameObject. It gets called from an event that is Invoked in another GameObject's Start().

ionic socket
quartz folio
#

Then you need to properly unsubscribe from it when your object is destroyed

ionic socket
#

hmm that makes sense but it's never being destroyed. And we're not running into the exception until we reach the Debug - ie, the method is executing (like this string Debug.log)

#

I guess it would make sense if it's persisting between Play sessions?

quartz folio
#

It's destroyed when the scene is

#

Yes

ionic socket
#

huh

quartz folio
ionic socket
#

I can't control unsubscribe because I'm arbitrarily ending play mode frequently during testing. Is there a way to make sure a System.Action resets itself on Play Mode?

quartz folio
#

Why can't you use OnDestroy?

ionic socket
#

does that get called when an exception is thrown or I dump out of play mode?

quartz folio
#

It'll get called when you exit playmode

ionic socket
#

hmm. I'm thinking turning off Enter Play Mode Options may be the culprit.

quartz folio
#

which should be easy

#
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void Init() => s_MyEvent = null;
surreal blaze
ionic socket
#

I use a goodly number of static events... and I turned off domain reload because getting into play mode was taking an unreasonable amount of time (although upgrading to latest LTS seems to have helped a lot). I wonder if that reload is so slow due to the high (not really - dozens, not 1000s) of static events?

quartz folio
ionic socket
#

CEPM?

quartz folio
#

The last page I linked documents static events and recommends using Application.quitting, either works

gaunt wren
quartz folio
surreal blaze
#

Yea addforcw

#

If I remember correctly, I left my house just very recently so I canโ€™t check my code, Iโ€™m just going off memory.

gaunt wren
#

assuming it is AddForce, have you tried applying a huge number to the force just in case?

ionic socket
gaunt wren
#

the only thing that comes to mind for why force isn't applied is when the velocity is overwritten

quartz folio
surreal blaze
#

I canโ€™t really test what you suggest right now, do you mind I message you later when I get home? So I can show you what I got?

gaunt wren
#

yeah sure. Though my suggestion though is pretty straught forward. It's just to see if enough force is being applied.

ionic socket
#

is this an issue with all forms of events? I use System.Action<T> instead of UnityEvent

gaunt wren
#

the other thing I can think of is the player's rigidbody isn't receiving the force but We'd need to see more of your script to know why

surreal blaze
#

Appreciate it. Thanks

quartz folio
ionic socket
#

makes sense

frosty silo
#

Hi, so, I'm coding a sound menu thingy for ym game and for some reason only the playerpref.get that is in the first line gets correctly issued to the sliders, what could be the reason and how can i fix it?

public void LoadVolumeLevels()
    {        
        uiSfx.value = PlayerPrefs.GetFloat("UI-SFX", 1);
        gameSfx.value = PlayerPrefs.GetFloat("GameSFX", 1);
        mainMenuMusic.value = PlayerPrefs.GetFloat("MainMenuMusic", 1);
        highlightSFX.GetComponent<AudioSource>().volume = uiSfx.value;
        selectSFX.GetComponent<AudioSource>().volume = uiSfx.value;
        inGameSFX.GetComponent<AudioSource>().volume = gameSfx.value;
        MenuMusic.GetComponent<AudioSource>().volume = mainMenuMusic.value;
    }
leaden ice
frosty silo
#

so like, put a debug.log after every playerpref line?

#

I tried this and i got all the in the console

public void LoadVolumeLevels()
    {        
        uiSfx.value = PlayerPrefs.GetFloat("UI-SFX", 1);
        Debug.Log("uisfx");
        gameSfx.value = PlayerPrefs.GetFloat("GameSFX", 1);
        Debug.Log("gamesfx");
        mainMenuMusic.value = PlayerPrefs.GetFloat("MainMenuMusic", 1);
        Debug.Log("menusfx");
        highlightSFX.GetComponent<AudioSource>().volume = uiSfx.value;
        selectSFX.GetComponent<AudioSource>().volume = uiSfx.value;
        inGameSFX.GetComponent<AudioSource>().volume = gameSfx.value;
        MenuMusic.GetComponent<AudioSource>().volume = mainMenuMusic.value;
    }
leaden ice
#

Print out the values of all these variables and what's coming out of PlayerPrefs and make sure it all matches your expectations

frosty silo
#

ok

leaden ice
#

print out some actual information

#

this tells us only one thing - that the code is running

frosty silo
#
public void LoadVolumeLevels()
    {        
        uiSfx.value = PlayerPrefs.GetFloat("UI-SFX", 1);
        Debug.Log(uiSfx.value);
        gameSfx.value = PlayerPrefs.GetFloat("GameSFX", 1);
        Debug.Log(gameSfx.value);
        mainMenuMusic.value = PlayerPrefs.GetFloat("MainMenuMusic", 1);
        Debug.Log(mainMenuMusic.value);
        highlightSFX.GetComponent<AudioSource>().volume = uiSfx.value;
        selectSFX.GetComponent<AudioSource>().volume = uiSfx.value;
        inGameSFX.GetComponent<AudioSource>().volume = gameSfx.value;
        MenuMusic.GetComponent<AudioSource>().volume = mainMenuMusic.value;
    }
leaden ice
#

ok so - does this match with your expectations?

frosty silo
#

nope

#

it should all be 3

#

like

#

1

leaden ice
#

looks like you have set them to 0 somewhere

frosty silo
#

but its weird, if i put the lets say gameSfx.value = PlayerPrefs.GetFloat("GameSFX", 1); line first, then i get 1 on that

lean sail
#

The number you provide is a default value if it doesnt exist

frosty silo
#

so it should be 1

leaden ice
frosty silo
#

ill send the whole code, wait

leaden ice
#

although you are making another mistake here which is printing gameSfx.value instead of directly printing the playerprefs return value

frosty silo
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class SoundManager : MonoBehaviour
{
    public GameObject player;
    public GameObject highlightSFX;
    public GameObject selectSFX;
    public GameObject inGameSFX;
    public GameObject MenuMusic;
    public GameObject musicInGame;
    public GameObject musicPowerUp;
    public GameObject musicDeath;

    [Header("Volume Sliders")]

    public Slider uiSfx;
    public Slider gameSfx;
    public Slider mainMenuMusic;
    public Slider inGameMusic;
    void Start()
    {
        LoadVolumeLevels();
        musicDeath.SetActive(false);
    }

    // Update is called once per frame
    void Update()
    {
        if (SceneManager.GetActiveScene().name == "InGame")
        {
            if (player.GetComponent<Movement>().inPauseMenu == false)
            {
                Death();
            }
            MenuMusic.GetComponent<AudioSource>().mute = true;
        }
    }
    public void ChangeUISfxVolume()
    {
        highlightSFX.GetComponent<AudioSource>().volume = uiSfx.value;
        selectSFX.GetComponent<AudioSource>().volume = uiSfx.value;
        SaveVolumeLevels();
    }
    public void ChangeInGameSFXVolume()
    {
        inGameSFX.GetComponent<AudioSource>().volume = gameSfx.value;
        SaveVolumeLevels();
    }
    public void ChangeMainMenuMusicVolume()
    {
        MenuMusic.GetComponent<AudioSource>().volume = mainMenuMusic.value;
        SaveVolumeLevels();
    }
    void Death()
    {
        if (player.GetComponent<Movement>().inPauseMenu)
        {
            //make some kind of tunnel sound effect
        }
        if (player.GetComponent<Movement>().isDead)
        {
            musicInGame.GetComponent<AudioSource>().mute = true;
            musicPowerUp.GetComponent<AudioSource>().mute = true;
            musicDeath.SetActive(true);
        }
    }
    public void SaveVolumeLevels()
    {
        PlayerPrefs.SetFloat("UI-SFX", uiSfx.value);
        PlayerPrefs.SetFloat("GameSFX", gameSfx.value);
        PlayerPrefs.SetFloat("MainMenuMusic", mainMenuMusic.value);
    }
    public void LoadVolumeLevels()
    {        
        uiSfx.value = PlayerPrefs.GetFloat("UI-SFX", 1);
        Debug.Log(uiSfx.value);
        gameSfx.value = PlayerPrefs.GetFloat("GameSFX", 1);
        Debug.Log(gameSfx.value);
        mainMenuMusic.value = PlayerPrefs.GetFloat("MainMenuMusic", 1);
        Debug.Log(mainMenuMusic.value);
        highlightSFX.GetComponent<AudioSource>().volume = uiSfx.value;
        selectSFX.GetComponent<AudioSource>().volume = uiSfx.value;
        inGameSFX.GetComponent<AudioSource>().volume = gameSfx.value;
        MenuMusic.GetComponent<AudioSource>().volume = mainMenuMusic.value;
    }
}

leaden ice
#
        PlayerPrefs.SetFloat("UI-SFX", uiSfx.value);
        PlayerPrefs.SetFloat("GameSFX", gameSfx.value);
        PlayerPrefs.SetFloat("MainMenuMusic", mainMenuMusic.value);```
#

you are setting the playerprefs here

frosty silo
#

yea but it isnt getting set unless i touch the sdliders

#

sliders*

lean sail
#

But you've set it at one point

leaden ice
#

and you've never touched them in your life?

frosty silo
#

i mean, yea ive touched them lol

#

but i delete the registry after every try

#

so i should be getting default on every run

leaden ice
#

you shouldn't be manually touching the registry if that's what you're doing

#

there's an option in the unity menus to reset the editor playerprefs

frosty silo
#

oh

#

i didnt know that

#

yes iw as deleting it manually lol

lean sail
#

You could also just add a temporary code to test it if you wanted to force values to be 1. As long as you remove it after

leaden ice
#

there's a separate one for the editor

frosty silo
#

yea i know

#

ive been deleting the one on the editor

frosty silo
#

ok

leaden ice
#

your slider could just be configured wrong

frosty silo
#

ill get back to u after a while

leaden ice
#

e.g. mx vlue of 0 or something

frosty silo
#

gotta do something

leaden ice
#
    public GameObject highlightSFX;
    public GameObject selectSFX;
    public GameObject inGameSFX;```
Highly recommend using direct AudioSource references here too
#

no reason to use GameObject for everything

#

just makes the code uglier with all the GetComponent calls

loud wharf
#

Yo, gonna ask smth, how do you stop an asynchronous function? I know of CancellationTokenSource but wondering for other ways. UnityChanThink

frosty silo
#

thanks!

frosty silo
honest jungle
loud wharf
#

I guess there's no other ways. ๐Ÿคท

mossy shard
#

is there any way to control the weight of an animation like you can control the weight of layers from code?

mossy shard
cosmic rain
frank wharf
#

Hello, I just cant change my sprite pixels per unit, sprite mode etc, no longer. The "Apply" button just is constant gray and not being able to be pressed. Even though I didnt change anything.

#

btw restarting unity sadly doesnt fix it

cosmic rain
frank wharf
#

Yeah i know, but I did try to change the pixel per unit

#

it just doenst let me apply it

cosmic rain
frank wharf
#

it feels like a sort of "project locking mechanism"

thin aurora
#

The only exception (pun not intended) is exceptions, which is why cancellation tokens throw an OperationCanceledException in basically all cases of c# internal methods when you cancel a passed cancellation token.

cosmic rain
loud wharf
thin aurora
#

You could argue that source generators are the second exception, but even those would inject a return; somewhere. A good example is probably EF, which does it in order to gather the relevant dependencies and such when you invoke migrations or anything else that requires it (I'm not actuall sure how they did it but that is the only explanation)

#

Useless info if you never used EF of course

thin aurora
cosmic rain
frank wharf
#

its also on every other sprite not just that one

thin aurora
#

Even Unity2023 adds support for it

nova crystal
#

does anyone know if there is a way to have an array of vector3s in shadergraph ?
or use an for loop
i need to add alot of variables to make my gersnerwaves look more realistic

ashen yoke
#

array of vectors sounds like a texture

#

however there is mat.SetVectorArray()

#

i assume there is a way

nova crystal
#

thx

nova crystal
#

@.cache do you know how to convert vectors to a 1d texture ?

ashen yoke
#

in c#?

nova crystal
#

yeah

ashen yoke
#

just dump as color into a buffer, feed into a texture through SetPixels

nova crystal
#

...

ashen yoke
#

there may be more optimal api now

nova crystal
#

speak english please

ashen yoke
#

i did

nova crystal
#

xD

#

ill try

#

thx man

ashen yoke
#

if you have concrete questions specify what exactly you dont understand

#

because i wont be guessing what is unclear to you

nova crystal
#

nvm found a solution

#

thx for ur help

lethal plank
#

damn i hate GetComponentInParent

#

stupid shit

rustic gyro
#

Does anyone here work with Unity VR? I have some questions about Input controllers for VR applications.

vital dust
#

And input.getButton

#

Look in Project Settings under Input to get the names, VR inputs usually start with "XR" or "XRI"

rustic gyro
vital dust
#

Okay, input.getKey should still work

rustic gyro
#

I have tried using Input.GetKey doesn't work because I tried using this in the if condition but it doesn't give any output with Debug.Log

devout harness
#

Does anyone have any resources or good pointers on where to look into circle collision resolution? I.e. If I have fifteen circles overlapping in one step, how to push them away from oneanother such that they no longer overap

vital dust
rustic gyro
#

No, If on KeyCode.Space

devout harness
ashen yoke
#

you will be essentially doing physics solver

#

iterations, depenetration, iterations, depenetration .. repeat every frame until there are no collisions

devout harness
#

Awesome thank you!

ashen yoke
#

@devout harness or you know

#

you could just use Bepu

#

straight up

#

assuming you cant use physics 2d for some reason

devout harness
#

I'm just exploring the process-- I figured I'd finally sit down and examine how it's done and try my hand at a worse one, but was very quickly stumped on the issue

ashen yoke
#

i understand

devout harness
#

I find it such an interesting problem, it seems extremely simple intuitively as a human but programatically is a nightmare

ashen yoke
#

yes and its not solved yet

devout harness
#

Ooooo interesting- there's not a fully optimized solution?

vital dust
#

So, I'm in a weird situation, I'll definitely want to learn C# at some point soon, however I already know most of it, except for syntax.

ashen yoke
#

physics engines i know will choke due to combinatorial explosion when there are too many colliding bodies

devout harness
#

Ahhhh okay, I take it that's a huge reason why fluid simulation is reserved for things like thousand dollar software on million dollar server farms at the highest quality level?

ashen yoke
vital dust
ashen yoke
#

static structures which dont require per entity resolution

vital dust
#

Flow rambles about learning C# (And some malformed C# code)

normal hedge
#

I am using the new Input system, and am trying to have adaptive Text like Press X to Y that changes depending on which Control Schema is Active. I currently get the text by action.ToInputAction().GetBindingDisplayString().ToUpper() where action is a InputActionReference. I however only get the text for one of the schemas. Is there a way to prefer one Schema over another that if it is available I get the corrosponding label? If that is not possible is there a way to print all possible bindings?

EDIT: found a way to get all binding using action.ToInputAction().bindings - with that you can then do binding.ToDisplayString() to get what I needed

lethal plank
#

wtf do they mean missing

#

i didnt even delete that

#

there is no script that delete Wpn object

pastel grove
#

Hi all! I'm trying to toggle a GameObject's material transparency on the fly, via code, analogous to what would happen if I were to switch the "Surface Type" from "Opaque" to "Transparent" in the first screenshot. Any ideas on how to do it? I tried it via the code you see in the second screenshot, but that had no effect.

swift falcon
ashen yoke
#

did you switch to hierarchy mode?

swift falcon
#

Yes

#

But I noticed that I can't try the profiler in build because it's an android game and unity doesn't detect my phone idk why

#

Here are some screenshots of the profiler, and of the hierarchy of the CPU

ashen yoke
#

hierarchy is sorted by cost

#

press arrows

#

expand

#

find whats eating up your cycles and generates most garbage

#

if its yours optimize it

#

if its not, google solutions or use different plugins

swift falcon
#

I noticed that sometimes over 50 percent is taken by URP, is it normal?

ashen yoke
#

dont know

carmine umbra
#

!code

tawny elkBOT
#
Posting code

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

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

cedar mist
#

When the player touches an invisible trigger it loads a map but whenever it is triggered the map loads multiple times (I have very little skill in coding atm and i dont know how to avoid unloading the player when switching scenes)

grim kiln
dusky cosmos
#
 void Update()
    {
        if (axeReturn)
        {
            if (time < 1f)
            {
                axeThrow = true;

                rbAxe.position = QuadraticBezierCurvePoint(time, oldPos, curvePoint.position, targetAxe.position);
                rbAxe.rotation = Quaternion.Slerp(rbAxe.transform.rotation, targetAxe.rotation, 50 * Time.deltaTime);
                time += Time.deltaTime;
            }
            else
            {
                ResetAxe();
            }
        }
}

[Command]
    public void ReturnAxe() //AnimationEvent
    {
        RpcReturnAxe();
    }

    [ClientRpc]
    void RpcReturnAxe()
    {
        rbAxe.gameObject.GetComponent<AxeController>().activated = true;
        time = 0f;
        oldPos = rbAxe.position;
        rbAxe.velocity = Vector3.zero;
        axeReturn = true;
        rbAxe.useGravity = false;
        rbAxe.isKinematic = false;
    }

I couldn't sync the ax's return

grim kiln
cedar mist
#

will it come back after the scene is reloaded?

cedar mist
#

kk

grim kiln
#

You could also use the non-async loading methods, which don't require unloading and don't take time, this will cause your game to pause while loading but you can probably deal with that for now.

swift falcon
#

How do I find the correct field of a material if I want to edit it?

For instance I am making a builder with a preview of what ur building so I want to change the surface type to "Transparent" but I can't remember how to find the key...

#

mat.Set???("Key?", Value)

#

I recall there is a window somewhere that shows all the information of a material?

potent sleet
thorny rock
#

I think that depends on the shader and is probably not build in Unity - an easy way to switch between the 2 is use a different material, and edit the .PNG to be 50% transparent instead

#

I am not great with shaders tho so don't mark my words ๐Ÿ˜‚

swift falcon
# potent sleet Ehh just swap materials

I want to maintain all the other settings like normals, smoothness, metallic, height, etc... etc... So I can do it that way but I'd need to then populate all the fields of a new material

Like this

previewMat.SetTexture("_BaseColorMap", newMats[ii].GetTexture("_HeightMap"));
previewMat.SetTexture("_HeightMap", newMats[ii].GetTexture("_HeightMap"));
previewMat.SetFloat("_DisplacementMode", 2);```
#

I rather do that ^ but just 1 field... but I forgot how you get it

forest linden
#

in unity what would take more peformance.

Using Vector3.Distance to check if a player is near enough on 100s of objects, or using a physics.overlap sphere to check if the player is near enough on 100s of objects

swift falcon
#

things like "_BaseColorMap" and etc are all exposed somewhere I believe? I just can't remember where

potent sleet
swift falcon
thorny rock
swift falcon
#

You could do it that way but yeh... I'd need to tie a preview variation to every normal material

forest linden
#

but thanks for the tip as I am always using vector3.distance and it is a heavy hitter

thorny rock
#

Yeah, you'd need Vector3.Distance if you'd like to know the exact distance between them. But if you want to know which one is closest. Just use Vector3.sqrMagnitude. A bit quicker.

#

Maybe a YouTube video is better at explaining it than Wikipedia ๐Ÿ˜› .

forest linden
#

My problem is the other way round, its 100+ objects individually checking if 1 object, the player, is close enough to interact.

#
if (Input.GetKeyDown(KeyCode.E) && !open)
        {
            if(Vector3.Distance(servermanager.localplayer.transform.position,transform.position) < playeropendistance)
            {
                open = true;
                Invoke("close", servermanager.boxregentime);
            }
        }
swift falcon
#

@thorny rock Okay from what I've read up, it seems that the editor does a bit of lifting internally when you swap the Surface type.

I think I'm going to just have a transparent "Base" material which I clone and then copy over the properties from the building I am planning to place. So similiar to what you suggested I guess? Thanks ๐Ÿ™‚

thorny rock
#

Saves you 100's of calculations each time you click on the button

forest linden
#

Its just my playerscript is already bloated with stuff for interaction

thorny rock
thorny rock
forest linden
#

I could have a interaction ghost script for each interactable object

swift falcon
#

Having objects check if a player is in range is pretty poor and makes scaling a nightmare though

#

Like you wouldn't have bullets fired and then all AI check if the bullet has hit them yet

thorny rock
#

Exactly. Thus the player script should simply check if the interactable is inside it's collider. So there's no check / caluclations at any time.

#

Only waiting for an event to trigger which is basically zero performance hit ๐Ÿ˜›

swift falcon
#

If you inherit from an abstract class like "Interactable", you can make different scripts like your door opening, searching something, breaking a window, etc... and then just call the ".use" function on them or something

#

If you do it this way, you don't have to worry about bloating your script, you can expand with it and it's efficient

#

By the way... I forgot exactly how but believe there is a way that you can create a temporary sphere collider and get everything it collides with? Not sure about the efficiency of it but if you have that happen when you click? That might be pretty good

frozen heath
# ashen yoke guid matches?

Thanks for the advice. turns out serializedreferences state the assembly that they can be found in, replacing this with Assembly-CSharp fixed them all

steep herald
#

is findobjectsoftype in awake safe?

#

in the "will it find all matching components that are enabled at scene load" sense

potent sleet
potent sleet
#

looks for the component

steep herald
#

Okay, was worried there could be scene load instantiates X before Y, X awake is called whilst Y is non-existent or some other race issues

upper patrol
#

Hey everyone, in my game i have a lock where i want to scroll the ui(the numbers) infinitely. I tried with a scrollrect to reset the ui position if it is bigger than ... but when I drag i get the transition is not fluent. I thought could be a way to change the uv position of the texture. But how can I do that with the scrollrect

steep herald
#

thank you @potent sleet

potent sleet
potent sleet
pure garden
#

any idea on this? it throws the error
method name expected
on the line with the red underline

forest linden
#

needa capital on Scoreboard

#

oh nvvm

#

im an idot

grim kiln
#

A few things wrong here

#

but I think in this instance you have rogue brackets, like you're calling a function, but that instance of ScoreboardDataClass isn't one

pure garden
#

without that unity gives the error
cannot convert void to ScoreboardManager.ScoreboardDataClass

grim kiln
#

I also suggest taking the word class out of your class name, and very taking the word class out of the instance name

#

You have two instances of ScoreboardDataClass, one called scoreboardDataClass and one called scoreboardDataIndex, which is very confusing

pure garden
grim kiln
#

the method you're calling on the List called Add is returning nothing

pure garden
#

wym

grim kiln
#

and you're trying to assign that to the scoreboardDataClass, that's why you're getting an error about voids

pure garden
#

yh i fixed it now

#

ig

#

just did this

#

tysm

swift falcon
#

Do all the people with "Unity Staff" develop the engine?

prime sinew
#

Unity is not only made up of developers

swift falcon
#

Well yeh but if someone works at Unity for marketing, their input is a bit different is why I asked out of curiosity

#

Thanks for the answer ๐Ÿ™‚

surreal blaze
#

Hello, wanted to ask is there anyway to have 1 animator controller be able to control 2 sets of animations?
Like I have a player and it has animations that it has a sword with and animations without it. I have some animations that are shared between but I want to swap between 2 layers (I plan to copy everything over and just change the sword specific animations to the melee ones) with like an event or a button. Would that be possible and how would I achieve that

trim schooner
compact spire
#

Should I just avoid using Enum's in my monobehaviors for the purpose of cleanly selecting options in the editor? If I need to reference the enum value through the Editor and say.. cast that to a string, it doesn't appear I can. Should I instead store just a string/int on the game monobehavior and then declare the enum in the editor and somehow override the dropdown selector for whatever the enum represented in the inspector?

trim schooner
#

Just use enums

compact spire
#

Then how do I get a string out of the enum value in the Editor?

trim schooner
#

why do you want a string of the enum in editor?

compact spire
#

updating the name of a prefab instance dynamically to kind of denote it's type at a glance..

trim schooner
#

you can just do .ToString() on an enum

compact spire
#

It won't work

trim schooner
#

What I dunno is how you'd get the selected enum from the inspector

swift falcon
#

I think .ToString() doesn't work if you manually set int values that are out of index

#

Or I could be confusing it with something else

compact spire
#

it gives me a boxing allocation error

#

beacuse the enum is defined outside the editor I think

thorny rock
#

I think we need a bit more information ๐Ÿ˜„

compact spire
#

I'm trying to pull the exact error

#

not sure how to copy it in Rider

trim schooner
#

screenshot it

compact spire
#

Boxing allocation: inherited 'Object.ToString()' virtual method invocation over the value type instance

thorny rock
#

Windows + shift + S

trim schooner
#

Show your !code too

tawny elkBOT
#
Posting code

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

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

compact spire
#

alright, gimme a moment

swift falcon
#

Btw Xitech I just found this lol

rugged goblet
# compact spire Boxing allocation: inherited 'Object.ToString()' virtual method invocation over ...

https://stackoverflow.com/questions/56785869/c-sharp-enum-tostring-boxing-resolve-or-supress

The boxing is because Enum.ToString calls the Enum.GetValue method, which returns the underlying value as an object - hence the boxing operation. The string is a reference type so it is not boxed. And just because of the string conversion no boxing would be necessary.

#

Essentially, if you're just running your code in OnValidate, you can just suppress that warning, more garbage to feed the garbage collector in the editor. Not very desirable at runtime.

compact spire
#

Supression worked

#

If it's under the Editor folder and using Editor dependences it shouldn't be executed at runtime anyways right?

rugged goblet
#

Yeah

compact spire
#

I don't plan on using it outside of the Editor

#

It might be worth swapping to a scriptable object or just an inherited type

#

Anyways, thanks everyone that helped ๐Ÿ™‚

mighty heart
#
public class MarkerPositionSaver : MonoBehaviour
{
    public GameObject markerPrefab;

    private GameObject parent;

    //Marker Position Speichern
    private List<Vector3> markerPosition = new List<Vector3>();

    void Start()
    {
        parent = new GameObject("Marker Parent");
    }

    void Update()
    {
        //Taste M muss gedrรผckt werden
        if(Input.GetKeyDown(KeyCode.M))
        {
            SetMarkerAtMousePosition();
        }
        
        if(Input.GetKeyDown(KeyCode.N))
        {
            DeleteMarkerAtMousePosition();
            Debug.Log("test1");
        }
    }

    private void DeleteMarkerAtMousePosition()
    {
        if (Physics.Raycast(Camera.main.transform.position + Camera.main.transform.forward * 2f,
            Camera.main.transform.forward, out RaycastHit hit, Mathf.Infinity, ~(1 << 6)))
        {
            GameObject marker = hit.collider.gameObject;
            if (markerPosition.Contains(marker.transform.position))
            {
                markerPosition.Remove(marker.transform.position);
                Destroy(marker);
                Debug.Log("Marker wurde gelรถscht an Position: " + marker.transform.position);
            }
        }
    }
}

Hello i want to delete a gameobject in my unity project when i hover over it and press the key N. But my DeleteMarkerAtMousePosition Function does not work and i dont know why. the function above creates these gameobejct in my game when i press m. Could somebody help e or give me an advice where my problem is pls ?

rugged goblet
#

I think the Enum class has a workaround for this, though.

gray belfry
#

Whats the best database to save data for unity besides firebase

rancid jolt
#

The weight of the animation Layer should be 1 when it's name and tag name name matched. But It is getting the index of -1. Although names are correctly matches and weight is 0 still

shell scarab
#

currently in tears that unity's serialized property has no support for short or ushort values

grizzled vine
#

I have a small problem I suppose.

I have a Util script that I originally made to configured to get Seeded Values from, that way, I could do a "seeded" run for my game. The problem is, it appears to be returning the same value every call, during the same frame.

Any good way to fix this?

//Sets up the spawn state to be constant.
    public static void InitSeed(int seed) {
        UnityEngine.Random.InitState(seed);
        seededState = UnityEngine.Random.state;
    }

public static float GetSeededFloat(float minInclusive, float maxInclusive) {
        //Set the last state.
        UnityEngine.Random.state = seededState;
        //Get the random number.
        float rand = UnityEngine.Random.Range(minInclusive, maxInclusive);
        //Store the spawn state.
        seededState = UnityEngine.Random.state;

        return rand;
    }
leaden ice
#

or at least the same sequence of values

grizzled vine
dusk apex
#

Shouldn't be an issue, are you changing the state elsewhere?

leaden ice
#

that would happen if you keep setting the state to the same value right before calling Range

grizzled vine
leaden ice
#

start Debug.Logging the seededState value

#

it should be changing each time

#

(log it before and after the Range call)

dusk apex
#

Only other thing I can think of is if you're reseeding every frame

hexed geode
#

how do i get accurate world-space mouse position delta? this is what i'm doing right now:

if (Input.GetMouseButton(2))
        {
            mouseMovement.x = Input.GetAxis("Mouse X");
            mouseMovement.y = Input.GetAxis("Mouse Y");
            cam.transform.position -= mouseMovement;
        }```
but the speed seems to change depending on the size of the screen and the orthographic size of the camera (because i think it measures it in pixels)
how would i get the actual world-space mouse position delta instead of the pixel one?
leaden ice
#

transform.position is in world space

#

you will need to convert first.

#

And that conversion depends on exactly what you're trying to do

hexed geode
#

so just cam.transform.position -= cam.ScreenToWorldPoint(mouseMovement); ?
no wait that will certainly break

leaden ice
#

basically "mouse world position" is always a bit ambiguous

leaden ice
#

Is it a 2D game?

hexed geode
#

yes

#

ok yeah this certainly does not work

leaden ice
#

you pbasically need to do this

hexed geode
#

i'm trying to make drag camera movement similar to what it is in the editor

leaden ice
#
Vector2 previousMousePos;

void Update() {
  Vector2 currentMousePos = cam.ScreenToWorldPoint(Input.mousePosition);
  Vector2 diff = previousMousePos - currentMousePos;

  cam.transform.position += diff;
  
  previousMosePos = currentMousePos;
}```
#

something like that

#

it might actually be -= diff

#

not sure

#

probably -=

hexed geode
#

i think i tried that and it made the camera fly out into float overflow xd
but i'll try it again with this, maybe i messed it up the first time

leaden ice
#

oh yeah

#

uh

#

there's an adjustment you need to do

#

because the camera itself moves

#
Vector2 previousMousePos;

void Update() {
  Vector2 currentMousePos = cam.ScreenToWorldPoint(Input.mousePosition);
  Vector2 diff = previousMousePos - currentMousePos;

  cam.transform.position -= diff;
  
  previousMousePos = cam.ScreenToWorldPoint(Input.mousePosition); // reset the "previous" position to the current so next frame there is no diff if there is no mouse motion
}```
#

something like this

hexed geode
#

let me try one sec

hexed geode
# leaden ice ```cs Vector2 previousMousePos; void Update() { Vector2 currentMousePos = cam...

ok this didn't work exactly but i added something and now it works perfectly, tyvm!

Vector2 previousMousePos;

    private void Update()
    {
        if (Input.GetMouseButtonDown(2))
        {
            previousMousePos = cam.ScreenToWorldPoint(Input.mousePosition);
        }
        else if (Input.GetMouseButton(2))
        {

            Vector2 currentMousePos = cam.ScreenToWorldPoint(Input.mousePosition);
            Vector2 diff = previousMousePos - currentMousePos;

            cam.transform.position += (Vector3)diff;

            previousMousePos = cam.ScreenToWorldPoint(Input.mousePosition);

        }
    }
``` - this is basically what i did
leaden ice
#

ah yeah you need to reset the positiojn when you press the button so it's not using some old one

#

My solution was ignoring the whole mouse button thing

somber ether
#

Q: For testing, would this be functional for checking internet? Regardless if its hotspot or wifi. Loads offline scene if no wifi.

leaden ice
#

yes generally making a simple web request and checking the result is a standard way to check connctivity

rugged goblet
#

Might actually be a good idea to have a second reliable URL you check, just so your connectivity isn't solely tied to google's uptime even if it is basically guaranteed right now

cobalt gyro
#

Does anyone know how i can do this with scripting

left crypt
#

Anyone know what the included fonts are?

my usage is this

Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;

soft shard
cobalt gyro
#

Thanks

soft shard
left crypt
#

So I can only use included fonts

soft shard
# left crypt Its not a project its a BepinPlugin

If your doing this in Unity, you can still use the Project window to find the fonts in your project, if this is entirely outside of Unity, im not sure how else you could find what your looking for, but Resources.GetBuiltinResource seems like a Editor function to me, so I imagine you have access to a project to use that API

left crypt
wooden knot
#

velocity.x = Mathf.MoveTowards(velocity.x, topSpeed * 60, topSpeed * 60 * acceleration * Time.fixedDeltaTime);

This is my movement code. I am wanting to be able to input a simple number for time to decide how long it takes to get to top speed. Currently in this, if I input 1 for acceleration I will arrive at top speed in 1 second, but I want to be able to say arrive at top speed in 1 second or 2 or .5 ... etc.

lost spoke
#

Anyone here know vector math? Red is the current vector, Blue is the desired vector

#

Proj is in 3d, if that matters

dusk apex
#

What's the relationship of blue to the other two?

#

If blue branched from the origin of green (the initial point) it would be an add operation - would imply you know the blue vector.

lost spoke
lost spoke
#

im trying to "flatten" the red vector

dusk apex
#

So we'd need to know more about the circle else there's little binding the vectors together.

#

How is red related to this?

lost spoke
#

There isnt a way to use green to cancel out the forward movement of red?

lost spoke
#

red is the current vector I am getting

leaden ice
# lost spoke

can you explain in words what you're trying to do?

leaden ice
#
Vector3 blueVector = Vector3.ProjectOnPlane(redVector, -greenVector);```
#

This^

dusk apex
lost spoke
# leaden ice That is vector projection

Sure, I have a camera, and when I click, I can drag a 3d object across the screen and I want it a consistant distance away from the camera (the original distance between the two), the way I did it before was I just overwrote the z axis to be the distance between the camera and the object, but if I rotate the camera, that doesn't work

dusk apex
leaden ice
soft shard
left crypt
#

title is the type of text

#

which is attached to a gameobject

soft shard
# left crypt which is attached to a gameobject

I dont think I understand your setup, GameObjects are specific to Unity, so your code would have to exist in a Unity project, and attached to a Game Object in a scene that has this "title" text component attached to said object, for any of your code to execute, it would have to be compiled by Unity or some other system (then that system has to know how to recognize Unity-specific code and API) which means you should be able to use the Project view to search, I think you can also search in a similar way with AssetDatabase (though thats in the UnityEditor namespace), in terms of just default fonts, without Unity itself, im not sure how else you can find anything aside from guessing Arial is likely a default font

left crypt
manic ether
#

hey guys can anyone help?

public async void TurnOffAfterTime(GameObject gameObject, float time)
{
await Task.Delay((int)(time * 1000)); // Convert time to milliseconds

    // Check if the GameObject is still active before turning it off
    if (gameObject != null && gameObject.activeSelf)
    {
        gameObject.SetActive(false);
    }
}

This is an async function which i am using to set an object disabled. The issue is that when i exits the play mode and now i am in the unity editor the thread completes itself and makes the object disable despite playmode exited. How can i avoid it from executing after playmode exited?

somber nacelle
#

cancellation tokens. or just use a coroutine if you aren't on 2023 to use Awaitable

manic ether
#

dont have an idea on cancellation tokens. I guess i ll do some research and come back

#

coroutine doesn't go with my usecase otherwise that's my first option

somber nacelle
#

if you use a coroutine you also wouldn't have to do that check to make sure gameObject isn't null or that it is active since a coroutine started on that object would be canceled if the object is destroyed or inactive

manic ether
#

thanks, I was getting an error while using coroutine thats why i used the async await. Turns out it was my mistake. The error was coming thought another thing that i now have fixed and the coroutine is working just fine. Thanks @somber nacelle

soft shard
# left crypt My setup is a visual studio project, using .net standard 2.0, with the unityengi...

Ah I see, so then you may only have the documentation to go off of: https://docs.unity3d.com/560/Documentation/Manual/class-Font.html if its not covered there, im not sure where else you might be able to find that info outside of the editor, though you could probably make a new project to search for the fonts or maybe theres a Unity Technologies github project that might contain them, though the version might matter, as I think later versions may use different fonts compared to older versions (though I could be wrong)

lost spoke
# leaden ice though for a consistent distance from the camera you can also do: ```cs Vector3 ...

Alright, I may be doing something wrong so I recorded a demo of my problem and pasted the code, the mousepos.z was my original solution, but moving/rotating the camera then it doesnt work as intended (first gif), just tried the plane projection but maybe i have done something wrong (second gif)

Vector3 dragPos = Input.mousePosition;
//dragPos.z = (cam.transform.position.z - grabbedObj.transform.position.z); // original z dist solution
dragPos = cam.ScreenToWorldPoint(dragPos);
Vector3 distVect = cam.transform.position - grabbedObj.transform.position;
Debug.DrawRay(grabbedObj.transform.position, distVect, Color.green);
//grabbedObj.transform.position = dragPos; // for z dist sol
grabbedObj.transform.position = Vector3.ProjectOnPlane(dragPos, -distVect); 
#

I figured the sol in the first gif was because of using .z and the camera wasnt on the z axis anymore, but could it be something else?

#

The first few seconds of the first gif is what is intended, just regardless of cam pos/rot

olive bear
#

Hi everyone !! I need some help !! I was Working on a mobile game and i implemented advertisement and it work fine , today I Implemented some post processing and to affect the UI I used the screen space - Camera on the canvas Renderer mode , then when ever I clicked the ads button it show mw this error : UnityEngine.Advertisements.Placeholder.HideSkipButton (UnityEngine.GameObject canvasGameObject) (at Library/PackageCache/com.unity.ads@4.4.2/Runtime/Advertisement/Platform/Editor/Placeholder.cs:182)
UnityEngine.Advertisements.Placeholder.Show (System.String placementId, System.Boolean allowSkip) (at Library/PackageCache/com.unity.ads@4.4.2/Runtime/Advertisement/Platform/Editor/Placeholder.cs:79)
UnityEngine.Advertisements.Platform.Editor.EditorPlatform+<>c__DisplayClass14_0.<Show>b__0 () (at Library/PackageCache/com.unity.ads@4.4.2/Runtime/Advertisement/Platform/Editor/EditorPlatform.cs:165)
UnityEngine.Advertisements.Utilities.CoroutineExecutor.Update () (at Library/PackageCache/com.unity.ads@4.4.2/Runtime/Advertisement/Utilities/CoroutineExecutor.cs:17)

olive bear
olive bear
tranquil viper
#

I'm trying to make sense of some code from a unity app, it has tons and tons of code that look like this

peak wing
#

How can i make two objects with same material but different colors?

olive bear
shell scarab
#

I have a static variable that is reset to its default value when accessed outside of the class it's in and I don't know why.

public static UnitDestroyData LastDestroyed { get; private set; }
    public readonly struct UnitDestroyData
    {
        public readonly int strength;
        public readonly float speed, health;
        public readonly System.Type type;

        private UnitDestroyData(System.Type type, int strength, float speed, float health)
        {
            this.strength = strength;
            this.speed = speed;
            this.health = health;
            this.type = type;
        }

        public static UnitDestroyData CreateUnitDestroyData<T>(int strength, float speed, float health)
        {
            Debug.Log(typeof(T));
            return new(typeof(T), strength, speed, health);
        }

        public GameObject Reanimate()
        {

            GameObject obj = new();
            var unit = (UnitData)obj.AddComponent(
                type.GetType());
            unit.Strength = strength;
            unit.Speed = speed;
            unit.MaxHealth = health;
            return obj;
        }
    }

It's set in an OnDestroy method:

    protected virtual void OnDestroy()
    {
        LastDestroyed = GetDestroyedData();
        Debug.Log("Destroyed");
        Debug.Log(LastDestroyed.type);
    }

those debug log statements are called, and it logs the correct type. Yet the very next debug log it's null, which is called from just a separate test class:

        StunnerUnit bu = new GameObject().AddComponent<StunnerUnit>();
        Destroy(bu);
        Debug.Log(UnitData.LastDestroyed.type); // null here

In addition, the strengh, speed, and health are all 0, even if directly set otherwise.
That makes no sense to me.

#

actually it's only null in the start method. What!?

somber nacelle
#

if it is only null in Start but you also only assign it in OnDestroy then what are you expecting to happen? ๐Ÿค” Start will obviously run before the object has been destroyed

shell scarab
#

no, on a seperate test object i have the very last code block.

#

but I think it's because OnDestroy doesn't immediately run.

#

yes that was the problem.

timber bluff
#

Does anybody know how i can "ensure you are signed in through the authentication sdk and try again"? ||context: I'm trying to setup cloudsave but i get thrown an exception stating my access token is missing, i cant provide code since no line or code is mentioned||
i did look around the docs, discord and other places and found nothing relating to the matter, and I ensured I was logged into services

spare island
#

When I change slider.value, the value doesn't actually change but if I debug.log(slider.value) it prints out the value I gave it

#

and in the inspector the 'Value' isn't different either

timber bluff
lean sail
spare island
#

like i said the actual value is 0 and now im actually more confused because i exposed the variable im setting the slider to

timber bluff
somber nacelle
spare island
#

i mean when i check the cached slider it matches up

#
   public byte CurrentObjectiveProgress
    {
        get => _currentObjectiveProgress;
        set
        {
            _currentObjectiveProgress = value;
            UpdateProgress();
        }
    }
    private void UpdateProgress()
    {
        slider.value = CurrentObjectiveProgress;
        Debug.Log("New progress:" + CurrentObjectiveProgress);
        Debug.Log(slider.value);
    }
#

i thought maybe it was because i was using byte but i changed it to float and that didnt change anything

somber nacelle
spare island
#

if i click the reference it highlights the object i expect it to

somber nacelle
#

then either something else is changing it back to whatever it was before this method you've shown runs, or you aren't showing enough actual context

timber bluff
#

in the inspector, drag the value manually and verify the slider ui actually does change as expected

spare island
#

it changes when i change the value

timber bluff
#

did it change ?

#

yes but i mean the sliders ui not the value itself

somber nacelle
spare island
#

idk what you mean by that

spare island
lean sail
spare island
#

it doesn't change back

#

if thats what you're checking for

timber bluff
#

manually changing the value in the inspector and making sure the ui changes accordingly

spare island
#

๐Ÿ™ƒ

lean sail
#

no need to suggest random things. literally every suggestion that can be provided right now is a guess. We need more context

#

also, learn to take a screenshot please

spare island
lean sail
#

literally all i have in my code to update a slider is

[SerializeField] Slider metallic;
// later on in some method    
    metallic.value = data.metallic;
#

which is just a float

spare island
#

im setting the value too but it doesnt do anything .-.

lean sail
#

do it on a new slider

spare island
#

i mean it does, somehow because if i do debug.log(slider.value) it gives the value i just gave it

somber nacelle
#

again, if it isn't showing the value you expect after you see that log, that means something else is changing it

spare island
#

ok well they are changing if i just set them to a random number every frame

somber nacelle
#

add this log to the beginning of your method
Debug.Log($"Slider {slider.name} - {slider.GetInstanceID()} current value: {slider.value}");
and this at the end of the method
Debug.Log($"Slider {slider.name} - {slider.GetInstanceID()} value {slider.value} matches {CurrentObjectiveProgress}: {Mathf.Approximately(slider.value, CurrentObjectiveProgress)}");
and show what each prints

somber nacelle
#

it's a prefab

spare island
#

so im changing values in an instance of a prefab?

somber nacelle
#

the instance ID would be negative if it were an in-scene object

somber nacelle
spare island
#

that doesnt make sense though because if i click the cached slider it highlights the in scene object

somber nacelle
#

you're likely reassigning the variable somewhere then

#

of course you haven't shown enough context for me to take a guess at where and all of the troubleshooting so far has really just been taking guesses at what the issue might be so ๐Ÿคทโ€โ™‚๏ธ

spare island
#

well now its negative

#

i can paste the code ig

somber nacelle
#

so something else is changing it if the values are not what you expect them to be

spare island
#

its a mess which is why i dont really wanna post it lol

#

i have a feeling its a problem with CurrentObjectiveProgress

somber nacelle
#

no, the issue is that some other object is assigning a value to the slider

spare island
#

thats not possible i dont think?

somber nacelle
#

why would that not be possible?

spare island
#

i only have one script that even references a slider

#

and its the one i posted

somber nacelle
#

the only location in that code you've shown where the slider's value is updated shows that it is being set correctly by this code but something else has changed its value between the time it was set and when you check it again

#

which is exactly why i gave you the logs to print. you can clearly see it is being set to 0 in this code, but then it is suddenly 9 from something else

hidden compass
#

Hello,

is this a position lerped to the grounded position during a step-off? A jump landing causes a screenshake rather.. but im curious of this mechanic.. i wonder how they decide when to lerp and when to act normal.. maybe checking horizontal velocity and under a threshold.. when it becomes !grounded it casts down to see how far its falling and if that is also under a threshold then lerp..

what do you guys think?

spare island
somber nacelle
#

right because that is not the issue. the issue is that the slider's value is being changed from somewhere that isn't the code you've shown

spare island
somber nacelle
#

apparently not

spare island
#

throughout the entire project

#

that is the one time i reference a slider

somber nacelle
#

and as the logs prove, this code is not the problem. it's some other code that runs between when this code runs that is causing your issue

somber nacelle
#

the fact that each time the method is called the slider's value is reset to 9

#

you're obviously not setting it to 9 in this code because the logs show you set it to 0 from here. so logically, the issue lies elsewhere

#

you can cry about how you are sure you aren't setting it somewhere else, but obviously something is affecting it that isn't the code you've shown

spare island
#

i think you might be getting confused by the multiple objectives

#

im going to set it to one objective

#

those logs were running once per each objective so the numbers would be pretty different

somber nacelle
#

okay well i'm done attempting to help since you prefer showing literally no context

#

like obviously the log for the beginning of the method was to show you the value before you set it each fucking time you set it

glass basin
#

I want to create a pathing system for a character, so whenever he hits a new tile there will be a random chance something happens. how would I do this>

rigid island
somber nacelle
#

A* algorithm for pathfinding since that is practically perfect for grid based pathfinding.
then you just need some way to determine when the object gets to a new tile, this can be done using physics messages/physics queries (where each tile would need its own collider), or simply checking the position against the tilemap to determine what tile it is on, distance checks, etc.

spare island
# somber nacelle and as the logs prove, this code is not the problem. it's some other code that r...
        public void AddObjective()
        {
            if (_objectives.Count == 255)
            {
                Debug.Log("Skipped creation of new objective due to hard limit.");
                return;
            }
            
            // TODO: Add code for adding objectives to the UI
            // Instantiate
            var newObjectiveNode = Object.Instantiate(objectiveUIPrefab, uitransform);
            
            // Rename
            newObjectiveNode.name = "Objective " + ((byte)_objectives.Count).ToChar();
            
            // Get objective UI node script
            //   VVVVVVVVVVVVVVVVV - Used objectiveUIPrefab instead of newObjectiveNode
            if (!objectiveUIPrefab.TryGetComponent<ObjectiveUINode>(out var uiScript))
            {
                throw new ArgumentException($"No {nameof(ObjectiveUINode)} found in instantiated prefab.");
            }
#

some weird dictionary reference shenanigans

glass basin
#

bro

#

im going to cry

#

i have no idea how to do this

spare island
glass basin
spare island
glass basin
#

yeah

#

i am on time pressure

spare island
#

it sucks

glass basin
#

this theme

#

is so shit

spare island
#

are u still in conception phase?

#

like u still dont have a concept

glass basin
#

im in the idk how to code advanced ai

spare island
#

big scope for 48 hours

glass basin
#

im going to win

#

but

#

idk how

lean sail
glass basin
#

i just need it to go up and down and check every tile

lean sail
#

you havent really provided context about what you're actually trying to do.
"whenever he hits a new tile there will be a random chance something happens" sounds literally like a position check to me

glass basin
#

ok ill explain

#

i want a game object to walk around the brown path

#

and i want it to check the tiles

#

and 1/5 chance it;ll spawnin smth

spare island
halcyon venture
#

in this code, does it affect physics? or does it just affect the render and not rigidbodies and colliders etc etc

glass basin
#

im just so confused how to do this though'

lean sail
rain minnow
lean sail
glass basin
#

thats the thing

#

and i don't know how to spawn a tile in in a tilemap through scripts

lean sail
#

follow tutorials, and break your problem down into steps. You were asking how to create a pathing system for your character with a random chance of something happening, but you dont have a character to start with

rain minnow
halcyon venture
zealous vector
#

I have a basic script that applies impulse force on the circle based on how far the mouse is dragged after clicking. However I'm assuming as the circle comes back down the velocity grows exponentially and thus makes it feel janky since the force applied is not enough to overcome the exponentially built-up velocity. If this is the case, is there a way to make it so there's not an exponential increase in velocity due to gravity? Rather a linear fall.

modern creek
#

I have an asset library that I like, and I copied it into a new project but left the meta files intact, and now all the fonts are broken. Is there any easy fix for this:

#

(should look like this:)

#

The TMPro font and atlas appears to be properly imported

mental rover
zealous vector
#

I fixed it with linear drag however i like this idea thank you

swift crypt
#

I have a simple class and part of it "escaped?" the script component
(Unity 2021.3.4f1)
Has this been fixed in a more recent unity version?

somber nacelle
#

are you on a really ancient version of 2021.3? because that was fixed in like patch 7

swift crypt
#

yes

potent sleet
#

so update xD

swift crypt
#

I'm just making sure, my internet is so slow its going to take a day

swift crypt
#

ok good

somber nacelle
#

ah even sooner than i remembered then lmao

reef spruce
#

Hello! I'm making an FPS game, this means that the main camera always has to be attached to the player.

My question is if anyone knows which is the best method to keep the camera attached to the player, because I can think of the two classic ones, which is to use a script that updates the position of the main camera always in the position of the player, or the Another option is to make the main camera a child of the player object.

And I ask this because the character uses Rigidbody (physics) to move, so I don't know if there will be some kind of conflict with movement using physics and any of the camera positioning methods. (I heard somewhere that making the child camera of the player object and moving it through physics was not a very good idea because it could cause bugs from time to time, so that's where my question comes from because I don't know if what I heard is true)

potent sleet
#

rigidbody controls the transform

#

if it's parented it moves with it

reef spruce
#

ty

gloomy stirrup
#

!manual

tawny elkBOT
rain minnow
slow shale
# glass basin

void OnTriggerEnter2D(Collider other){if(nm.isStopped){//check tile}}?

#

bassicly have a trigger with the size of a tile

#

make the ai move to the middle of the tilw

#

when is stopped check tile

#

also you could check the tag aswell to make sure

gray mural
#

just wanted to ask if this is efficient to catch user's input like this:

private void OnGUI()
{
    Event evt = Event.current;

    if (evt != null)
        CheckEventType(evt);
}
#
private void CheckEventType(Event evt)
{
    switch (evt.type)
    {
        case EventType.KeyDown:
            KeyDownEvent(evt);
            break;
    }
}
#
private void KeyDownEvent(Event evt)
{
    switch (evt.keyCode)
    {
        case KeyCode.Backspace:
            BackspaceKey();
            return;

        case KeyCode.Delete:
            return;
    }

    ValidateInput(evt.character);
}
surreal blaze
#

is there a way to get the gameobject a raycast2d is hitting?

this is what im having right now

            //Debug.Log(_hit.transform.name);      
            if (_hit )
            {
                Draw2DRay(parent.transform.position, _hit.point);
                Debug.Log(_hit);
                _hit.transform.gameObject : GameObject;
            }
            else
                Draw2DRay(parent.transform.position, new Vector2(defDistanceRay, parent.transform.position.y));```
quartz folio
surreal blaze
quartz folio
#

That is not valid C#, so I have no idea what would recommend that

surreal blaze
#

how would i get the gameobject then

gray mural
quartz folio
#

Declare a variable like you would normally

surreal blaze
#

oh

Is it really that simple

gray mural
#

that's GameObject property of _hit

gray mural
surreal blaze
surreal blaze
#

didnt work

#

uh

quartz folio
# surreal blaze

If your IDE isn't giving you error underlining and proper autocomplete you need to configure it !ide

tawny elkBOT
#
๐Ÿ’ก IDE Configuration

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

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

โ€ข VS Code*
โ€ข JetBrains Rider
โ€ข Other/None

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

surreal blaze
#

oh please

it works on my lpatop but not my pc

gray mural
surreal blaze
#

thank god for this

surreal blaze
quartz folio
surreal blaze
#

i meant like it works on the lpatop

#

but yea

#

same thing

#

will go do it

#

thanks @gray mural

#

@quartz folio

gray mural
#

if you cannot access gameObject - first access its tranform, then gameObject from transform

blabla.transform.gameObject;
surreal blaze
#

i see

#

@quartz folio it works now i got intelisense now

#

apperciate it

rain minnow
#

oh, wow. discord didn't update. i see it's all resolved now . . .

surreal blaze
#

everything works now

delicate whale
#

Hello, is there a way to detect when a user presses any number on the keyboard (not num pad) from 1-9 without writing a check for every single line?

#

normally, for 1-2 buttons i would do Input.GetKeyDown(KeyCode.Alpha1)... , but I want to make it so it's scalable between 1-9 for an inventory on screen and quick select items

#

I just skimmed through the autocomplete options and I found one that says Input.inputString, but upon further examination i realized that it just says "1" "2" "3"

#

there is no way to detect if it's actually from the numeric pad and not the top row keys

fervent furnace
#

i havent written anything that similar to this, but i think keycode is enum and probably alpha0,1,2,3.... is continuous so you may use a for loop to check (if(input.getkeydown(i)), i belong to alpha0+[0,10) ), please check the value of alpha 0 1 2 3 4 first if they are discrete then no ways

#

or you just want an array for mapping idx0 mapped to alpha0 1 mapped to alpha1...etc

vital dust
#

wanna see some stupid C# code made by a person who doesnt know C#?

swift falcon
#

Anyone know why there's a big jump in time during Task.Yield() here?

private async void Start()
    {
        await TransAsync(0);
    }

    public async Task TransAsync(float target)
    {
        float elapsed = 0;
        float dur = 0.5f;

        Color start = _trans.color;
        Color end = new Color(0, 0, 0, target);

        while (elapsed < dur)
        {
            float curved = M_Extensions.CosCurve(elapsed / dur);
            _trans.color = Color.Lerp(start, end, curved);
            Debug.Log(_trans.color + " " + elapsed/dur);

            elapsed += Time.deltaTime;
            await Task.Yield();
        }
        _trans.color = end;
    }```
vital dust
swift falcon
vital dust
#

yeah

swift falcon
#

Well alright then if it's such a beginner problem wanna offer an answer

vital dust
vital dust
winged mortar
winged mortar
vital dust
#

im not looking for advice -_-"

winged mortar
vital dust
#

but its code related

swift falcon
# winged mortar I don't know enough about tasks to fully answer this question, but im sure that ...

Mm yeah coroutines are normally the go-to but for stuff like transitions I use tasks to wait until the screen is black before saving/loading/etc. Not sure what way others do it but in my last game it seemingly worked fine. There's probably an issue with Task.Yield() being delayed for a good 0.25 seconds or so while Unity does something in the background

Anyways by increasing the duration from 0.5 to 2 it made the problem basically unnoticeable, I'm in a game jam so don't have time to make things perfect

winged mortar
swift falcon
wide dock
#

Moved to [#โ†•๏ธโ”ƒeditor-extensions](/guild/489222168727519232/channel/533353544846147585/)
wide dock
#

Oh ok

jovial moon
#

โ #archived-urp messageโ  I'm not sure if this counts more as shaders or urp or even code so I'll post it here also! Please do let me know where it would've been most appropriate so I can "spam" less in the future ^^

Discord

Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.

tight fjord
#

Any idea, why this ball is not moving with the same position like the third bone of this lamp?
It should copy the position from "X" and "Y" while "Z" remains the original of the Ball.

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

public class COPY_LightbulbBonePosition : MonoBehaviour
{
    [SerializeField] private Transform _LightbulbBone;
    [SerializeField] private Transform _Pusherball;
    void Update()
    {
        // clone the "new" coordinates into the Pusherball Object transformation:
        _Pusherball.transform.position = new Vector3(_LightbulbBone.position.x, _LightbulbBone.position.y, _Pusherball.position.z);
    }
}```
winged mortar
#

Isnt this offset of the bulb on the Z axis? If so then you should not keep the z position of the pusherball but instead use the z pos of the lightbulb

#

simply doing _Pusherball.transform.position = _lightbulbbone.position should work

winged mortar
#

recommend that you do this in LateUpdate though, as you have little control over the script execution order

winged mortar
winged mortar
#

Screenshot please?

lean sail
#

My first assumption is this is probably some weird parenting issue because the hierarchy shows the sphere as a separate object

winged mortar
#

wouldnt matter, as transform.position is world position anyway

vital dust
#

i feel like an idiot

lean sail
winged mortar
lean sail
#

Although im just guessing. The code cant really have an error of not copying the x and y unless something visually isnt where its parent is

winged mortar
#

Oh wait, nevermind i didnt take enough of a detailed look at the hierarchy! That could definitely be it, the pusher sphere might have a localposition set, good shout!

tight fjord
# winged mortar Screenshot please?

Its not moving at all with the position of the third bone, also my offset is now gone, thats why I only want to move X and Y while Z remains the original so I can push with it as animation later on.
This script should make the ball always move to the bones X and Y so it can always be pusshed.

lean sail
#

Honestly on mobile this is too hard to watch.

winged mortar
#

Check if "LightBulbPusherSphere" does not have a transform value set

#

Yeah watching videos is awful for debugging

#

Looks like he has physics on it too

#

Remove the physics from the actual model @tight fjord

#

And you might have to use rigidbody.moveposition instead of directly letting the transform

#

Hes also using some magicsphere script or something, idk if thats a library or something

tight fjord
winged mortar
#

Im talking about the sphere that you aim to move

tight fjord
#

I want that sphereHolder moving always to the same position like bone.003

lean sail
#

Honestly I dont even get what the video is supposed to show

#

Isnt the sphere supposed to copy the lightbulb bone, why try to move the sphere and not the lightbulb

tight fjord
lean sail
#

Wasnt that the goal, for it to copy the x and y

#

Which it was doing in the video

winged mortar
#

This is probably some physics stuff where the position keeps getting overwritten

tight fjord
winged mortar
#

why do you not care about the Z postion?

#

Again, the sphere is bouncing on the lamp aswell because they are both physics objects

#

So you need to to either ensure that they ignore eachother, or remove physics from one of the two

tight fjord
#

Z is used for later, thats why I want to move the HOLDER of it and not the ball itself.
I will make later a animation to move fast the "Z" axis forward/backward, to push the lamp, so it is looking if you pushed the lamp with your mouse. and I want to push the lamp even if it was already pushed, so the ball needs to move at the same X & Y like the bone.003

craggy cedar
#

I'm getting the error The targets array should not be used inside OnSceneGUI or OnPreviewGUI. Use the single target property instead. and I'm not sure why

WaypointPathEditorData data;
List<Vector2> pathData = new();
private void OnEnable()
{
    data = (WaypointPathEditorData)ScriptableObject.CreateInstance(typeof(WaypointPathEditorData));
}
(...)

public void OnSceneGUI()
{
    Event e = Event.current;

    PathEditor.DrawPath(ref pathData, e, ref data.TempPath, data.IsReplace);
}
winged mortar
#

You can simply apply a force to the physics object, and it wouldn't matter what the z position is

#

Feels like we are encountering this right now

tight fjord
# winged mortar So? This really depends on how you want to apply the force down the road

my hope was that this tiny script should do it:

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

public class COPY_LightbulbBonePosition : MonoBehaviour
{
    [SerializeField] private Transform _LightbulbBone;
    [SerializeField] private Transform _Pusherball;
    void Update()
    {
        // clone the "new" coordinates into the Pusherball Object transformation:
        _Pusherball.transform.position = new Vector3(_LightbulbBone.position.x, _LightbulbBone.position.y, _Pusherball.position.z);
    }
}

it should get the transform of the bone.003 and the transform of the ballholder and change the ballholders position to the same like the bone.003 so it does always cover the lamp, if to look at it in the 2D perspective, no matter how it is bouncing, cause it always moves in front of the lamp (bone.003=

winged mortar
#

This will never work because both are physics objects

lean sail
tight fjord
tight fjord
lean sail
#

Where, I dont see any debugs in the code

#

The inspector values are local position. You wont be able to compare those by looking at it

#

Really you should take this copy xy code and apply it to a basic cube with no rigidbody, maybe even further away from the light. Move the light and check if the cube follows.

tight fjord
#

it should looks like this, if the lamp is moving, the X and Y of the ball should always cover the lamp from the 2D canvas perspective.
(I paused it, so I can take this "fake" screenshot, cuase it is not doing what I want)

winged mortar
#

Alright so first things first, two physiscs objects trying to move into eachtoerh will cause them to continiously bump eachother (what happens if you try to compress two balls in real life to the same position?)

Then there's also a portential problem that your current way of moving directly accesses the transform, instead of using the related physics components for that - thus resulting in it immediately being overwritten by the physics engine

#

And then you also make a big deal about maintaining the current Z position, which does not matter for your usecase

#

only complicating the problem for yourself further

tight fjord
winged mortar
#

Then maybe try any of the suggestions we gave in the past 15 minutes?

#

Instead of repeating the same question over and over

lean sail
#

Try this on an empty cube. I have no clue what's happening in the hierarchy of that sphere. It has a child and a random component I've never seen

tight fjord
winged mortar
#

because you have supplied very little context, and are asking about an attempted solution rather than explaining your goal, what you've tried and what you are currently stuck on

lean sail
#

Maybe try repeating it for the 10th time. Im sure saying you want to copy the x y position again will change something

#

The code itself is trivial. The issue is within the setup

#

As we've been trying to help you debug

#

Have you actually added a debug statement, checked if the child sphere had any offset, or tried this on a basic cube like we've suggested?

tight fjord
# winged mortar because you have supplied very little context, and are asking about an attempted...

I use MagicaCloth2 for the physics of it.
My goal is it to make not only a lamp that moves by wind a tiny bit in the title screen, the Player should also be able to click with the mouse on the lamp to "push" the lamp and make them swing around.
To make this happen, I made a sphere with a magicacloth2 collider that can interact with the bones of this lamp (including the wire) But I don't just want to push the lamp if it is mostly standing still so the "pusherball" is in front of the lamp, I want to make the player even push the lamp even more, if it is already swinging, so the ball needs to swich at the same X and Y position of the bone.003 of the lamp, so that I can push with a animation the ball its Z axis to the lamp.