#archived-code-general

1 messages · Page 127 of 1

arctic spindle
#

Ohh oops, thank you

peak marsh
#

Is it a normal practice to launch many copies of same coroutine?
Will it cause some problems (except problem to store cache of all of them)?

trim schooner
#

Starting a coroutine creates a new ienumerator , so it's a new object(?).. you can have as many as you want running. It's also no problem to cache them, just cache in a list

#

You only need to cache them if you need the ability to stop them

sharp root
#

Hi , does someone know how i can do some code every 5 scene changes? So basicly every 5 scenes i do something.

dark sparrow
#

Just make an object that doesnt destroy on scenechanges and plus some int value by 1 every scene change and then do something

sharp root
#

How do i make an object that doesnt destroy on a scene change

dark sparrow
sharp root
#

Thanks , im acctualy trying to display Admob ads every 5 scene changes (Interstitial) , however they dont show for some reason. Ill try do implement this DontDestroyOnLoad

prime sinew
sharp root
#

Could you maybe give me an example of how that works?

prime sinew
prime sinew
# sharp root Could you maybe give me an example of how that works?

Watch this video in context on Unity Learn:
https://learn.unity.com/tutorial/statics-l

Statics are methods, variables, classes that aren't instanced. This means that methods and variables declared as static will belong to the class specifically and will be shared by all objects of the class. Classes declared as static will not be able to be ins...

▶ Play video
#

I assumed you knew about statics because you asked in code general,not beginner

#

Basically static variables aren't tied to any instances(in this case GameObject). So when the objects are destroyed on scene change, it won't get lost

#

Then I hope you can Google how to detect when a scene is changed

sharp root
#

Ok i kinda figured it out

#

@prime sinew How do i now Up the value of the public static int every time the scene changes?

knotty sun
#

same way you increment any int only you use the class name not an instance variable name

sharp root
#

Hmmm , could someone try to see the problem here?

#

Heres my SceneTracker script

#

`using UnityEngine;
using UnityEditor.SceneManagement;

public class SceneChangeTracker : MonoBehaviour
{
public static int counter = 1;

public void Update()
{
    if(counter % 5 == 0)
    {
        AdsManager.Instance.ShowAd();
    }
}

}`

#

When the int can be divided by 5 show the ad

#

And at the start the int is 1

#

oh man why would you post a video in the middle of me showing my problem

#

jeez

lethal plank
#

oh sorry

sharp root
#

its ok

lethal plank
#

yeet

sharp root
#

Just a sec

lethal plank
#

have you try debug?

sharp root
#

No

narrow summit
#

What kind of a type is a System.Single&

knotty sun
#

so where do you increment counter

sharp root
#

So i up the value of the counter in my other script where i have all the levels of the game

#

So when a level is loaded

#

The int goes +1

lethal plank
#

static

knotty sun
#

that is the script we need to see

sharp root
#

Its huge but heres the main thing

#

public void level1() { SceneManager.LoadScene("Level1"); SceneChangeTracker.counter ++; }

lethal plank
#

can static able to edit?

sharp root
lethal plank
#

i thought static can not change

leaden ice
#

readonly / const can't change

#

static means it belongs to the class, not an instance

knotty sun
lethal plank
#

oh i forgot

sharp root
lethal plank
#

kinda weird sheet

sharp root
sharp root
lethal plank
#

ye i dont even know how and why XD

#

also tried world to screen and somehow my object shaking

sharp root
#

Dang these Admob interstitial ads are really getting on my nerves

knotty sun
sharp root
#

The one where i have my levels?

knotty sun
#

no the tracker

sharp root
#

No

knotty sun
#

then how can you know what is not working?

sharp root
#

Youre right

#

But where should i add them

knotty sun
#

1 in start to show the script is active
1 inside the if to show it's being fired

potent sky
#

Hello.
I am currently using AudioTrack in Timeline to play sound.
When I pause the game, I set Timeline Speed to 0.
If I set the timeline speed to 0 while playing an AudioClip and leave it for more than 10 minutes, the AudioClip will not resume when I set the speed to 1.
Why is this?

lethal plank
#

may be it paused?

sharp root
#

Maybe i should put one to see if it acctualy ads the +1 to the int

knotty sun
#

maybe better rather than spamming the console to add some code to show a debug when counter changes

sharp root
#

Man

#

I really cant understand whats going on here

lethal plank
#

try figure it yourself
i have been figured my code why it is not working for a month

potent sky
# lethal plank may be it paused?

I understand that sound doesn't play when you pause.
When I unpause, the sound does not play.
If I call PlayableDirector.Evaluate, the sound will play.

unborn fern
#

so im trying to implement Discord RPC to my game and i tried a couple of times with the script being different everytime but nothing works, can anyone help?

using Discord;
using UnityEngine;
using UnityEngine.SceneManagement;

public class DiscordController : MonoBehaviour
{
    public Discord.Discord discord;

    void Start()
    {
        DontDestroyOnLoad(gameObject);
        discord = new Discord.Discord(SOMEGAMEID, (System.UInt64)Discord.CreateFlags.Default);
        var activityManager = discord.GetActivityManager();
        var activity = new Discord.Activity
        {
            Details = "Some Details.",
            State = "In " + SceneManager.GetActiveScene().name,
            Assets =
            {
                LargeImage = "testicon",
                LargeText = "SomeLargeText."
            }
        };
        activityManager.UpdateActivity(activity, (res) =>
        {
            if(res == Discord.Result.Ok)
                Debug.Log("Discord Status Set!");
            else
                Debug.LogError("Discord Status Failed!");
        });
    }

    void Update() 
    {
        discord.RunCallbacks();
    }
}
lethal plank
#

so i did it
and wondering how to get rid of no need parts
might be there is another way to create that circle through scripts or some kind of funny layer

#

anyone know how to create circle or layer?

sharp root
#

I figured out what i did wrong

#

Basicaly the GameManager script contains a list of levels where i put the int to go +1 , But that only happens when the levels buttons are clicked (im dumb) and so i tried clicking 5 level buttons and it worked .

#

Now i have a diffrent problem

lethal plank
#

nice

sharp root
#

Nice , now it works when i click the continiue button which i wanted in the first place

#

The only problem is that the ad gets displayed for a split second and dissapears

#

and it pauses my game as i can see

hollow musk
#

Hey all, I understand that a child can override a method in an inherited parent method with virtual / override, is there a version of this where instead of overriding, it calls both? so when Method() is called in the parent, the child of the parent class then does something extra on top of Method() (without having to add SendMessage or anything in the parent). Thanks in advance hope my question makes sense.

heady iris
#

the child can invoke the parent's method

#

but you can't force that to happen (without using reflection, at least)

dusk apex
leaden ice
steep herald
#

@dusk apex Oh what

#

News to me, can you give an example you have me excited

leaden ice
#

I don't think Dalphat understood the question properly TBH

#

Hiding the parent method with new will not be called at all when you invoke the method from a reference of the parent type

hollow musk
steep herald
#

@leaden ice 's answer solves your problem. If you want to FORCE the parent class to run regardless of the child class implementation, what you can do is

public void Foo()
{
    // Do Stuff
    OnFoo();
}

protected virtual void OnFoo() { }
steep herald
#

And override the OnFoo instead

dusk apex
#

I misread it stating that he wanted to be able to call both individually from a method - the misinterpretation.

stark jacinth
#

!code

tawny elkBOT
#
Posting code

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

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

stark jacinth
dusk apex
#

If it's a float and computed, it might not ever possibly be equal to zero.

knotty sun
stark jacinth
#

yea I had to make the value less then 0, so then when the flashlightbattery == 0 the flashlight turns off

#

when I did >= 0, it had the same problem

knotty sun
#

0 is an int 0f is a float

stark jacinth
stark jacinth
knotty sun
#

no, you should never check floats for equality

stark jacinth
#

howcome ?

knotty sun
#

because of float imprecision. 0.0000001 is not == 0f

dusk apex
#

10f/2f likely isn't 5f

acoustic sinew
#

I'm trying to think of a way to make sure premade rooms are rotated in the right direction for their openings to match. I'm not sure how to implement a system to do this

stark jacinth
#

I used Mathf.Approximately, but it still does the same thing

#

the flashlight wont turn off

dusk apex
#

Log the value of the battery before that if statement

#

See if it's what you think it is

mellow sigil
#

You have to check if it's < 0 because there's nothing that would stop it from going below that

stark jacinth
#
 if (off && Input.GetKeyDown("f") && battery.flashlightBattery > -0.1)
        {
            flashlight.SetActive(true); 
            //Turn on sound here

            off = false;
            on = true;

            //If battery level reaches 0 we turn off the flashlight 
            if(Mathf.Approximately(0,battery.flashlightBattery))
            {
                off = true;
                flashlight.SetActive(false);
            }

          

        }
#

this is the whole thing

mellow sigil
#

also the check is in a block that requires that battery.flashlightBattery > -0.1 so it has to be exactly between -0.1 and 0 which is very unlikely

stark jacinth
#

if the battery is greater than -0.1 then it turns on

dusk apex
#

I was assuming he was okay with negative values

#

What if it's -10

#

None of the statements would occur

stark jacinth
#

if my max battery life is 100f

mellow sigil
#

no it doesn't

dusk apex
#

And you or we would not know because there were no logs

#

Log the battery value

stark jacinth
#

so I should prnt out of current flashlightbattery to see what its doing

#

ok let me do that

dusk apex
#

Yes and to see if it actually even gets there

mellow sigil
#

and this check requires that you've pressed the f button on the exact frame when the battery is exactly 0

#

there's so much wrong with this logic

static matrix
#

will using goto to go to the top of a function cause recursion?

mellow sigil
#

also why do you have separate on and off variables, makes no sense

stark jacinth
dusk apex
#

@stark jacinth Maybe clamp the battery value

steep herald
#

@stark jacinth If the step (drain * deltaTime) is greater than your epsilon, there's a chance it'll skip that range and you'll miss that condition.

Instead of subtracting, use Mathf.MoveTowards(), this will ensure you never skip your target value

mellow sigil
#

it checks it when the condition off && Input.GetKeyDown("f") && battery.flashlightBattery > -0.1 is true

#

if you're not pressing f then it's not true

stark jacinth
#

and while you've already turned on the flashlight as the battery is draining if the battery equals 0 then it shuts off

mellow sigil
#

then why is the check that turns it off inside that check?

stark jacinth
#

because when you turn on the flashlight the battery starts draining

#

if it equals 0 your flashlight is dead

#

so it turns off

knotty sun
#

but only if the key is pressed

mellow sigil
#

Yes, that's what you're trying to do, but that's not what the code does

steep herald
#

His point is that this will never fire unless the user is pressing F down at that exact frame

dusk apex
stark jacinth
dusk apex
#

In your update

stark jacinth
#

ohhh

dusk apex
#

You're only attempting to turn off when you turn it on - not while it's on

stark jacinth
#

it has to be off to turn it on

knotty sun
#

irl what happens to a flashlight if you turn it on and just leave it?

stark jacinth
#

it eventually dies out

knotty sun
#

yes, no keypress required. so why are you checking the battery only when there is a keypress?

heady iris
#

didn't we go over this yesterday

acoustic sinew
#

Is there a way to rotate the Z axis to point out the doorway for me to use that as a forward check?

heady iris
#

the battery should drain in Update, not in the function that's only called once when you turn it on

mellow sigil
#

jesus christ
you have

if (off && Input.GetKeyDown("f") && battery.flashlightBattery > -0.01) {
    if(battery.flashlightBattery == 0) {
        ...
    }
}

it should be instead

if(battery.flashlightBattery < 0) {
    ...
}
else if (off && Input.GetKeyDown("f") && battery.flashlightBattery > -0.01) {
    ...
}
heady iris
#

oh, i suppose you did change that

#

it's the same kind of issue, though: you should always check if the battery is dead

#

not just checking when you actually try to turn it on or off

steep herald
#

@mellow sigil We all started somewhere, breathe

stark jacinth
#
  if (Input.GetKeyDown("f") && battery.flashlightBattery > 0.1)
        {
            if (off)
            {
                flashlight.SetActive(true);
                //Turn on sound here
            }
            if (on)
            {
                flashlight.SetActive(false);
                //Turn off sound here 

            }

        }

        //If battery level reaches 0 we turn off the flashlight 
        if (Mathf.Approximately(0, battery.flashlightBattery))
        {
            off = true;
            flashlight.SetActive(false);
        }
#

what about this logic ?

#

if you press f and off is true it turns on

#

vice versa it turns off

#

but if the battery equals 0 then the flashlihgt turns off

dusk apex
#
if button pressed and is off and not battery empty 
    turn on
else if is on and battery empty
    turn off```
stark jacinth
#

like this?

dusk apex
#

I think you should try what you had before

knotty sun
#

although I see absolutely no reason for doing so

stark jacinth
#
 if (off && Input.GetKeyDown("f") && battery.flashlightBattery > 0.1)
        {
            flashlight.SetActive(true);
            //Turn on sound here

            on = true;

        }
        else if(on && Input.GetKeyDown("f"))
        {
            off = true;
            flashlight.SetActive(false);

            //turn off sound here 

        }
        //If battery level reaches 0 we turn off the flashlight 
       else if ( on && Mathf.Approximately(0, battery.flashlightBattery))
        {
            off = true;
            flashlight.SetActive(false);
        }
#

I wrote this and it still wont turn off when the flashlightbattery equals 0

knotty sun
#

instead of

if ( on && Mathf.Approximately(0, battery.flashlightBattery))

why not just

if ( on && battery.flashlightBattery < 0.01f)
stark jacinth
knotty sun
#

did you also set on to false?

stark jacinth
#
 else if ( on && battery.flashlightBattery < 0.01f)
        {
            off = true;
            flashlight.SetActive(false);
        }
#

well yes

knotty sun
#

no you didn't

stark jacinth
#

but my UI doesnt disapear

#

what howcome??

knotty sun
#

i see no on=false; there

stark jacinth
#

oh just becasue off = true doesnt mean on == false;

steep herald
#

@stark jacinth Hey, you have 2 different variables to track a single state that can be represented by a binary value. This is awful design, will confuse you and get the best of you.

knotty sun
#

you made 2 bools where 1 is enough

stark jacinth
#

yea I should just keep on

#

and set it to true and false

knotty sun
#

yes

#

or even an enum would work

stark jacinth
#

but good news it does work, thank you Steve I really appreciate it

wispy nacelle
#

How to set the asset bundle that an asset is in automatically?

wintry schooner
#

Is it me or is the Range attribute very buggy? When setting the number manually, it fails to save if I click away. Furthermore, if I drag the slider, the nob tends to randomly disappear at higher (but inside the range) values. Very confusing. I feel like this didn't used to be a thing, is there something borked on my end or is this normal?

hollow musk
wintry schooner
#

Depends on what the answer is lol

potent sleet
#

What? Show the code which relates to this then

wintry schooner
#

Literally just [Range(0,1)] public float someValue;

#

Just wanna know if it's normal for it to behave like that, feels pretty buggy

potent sleet
#

can u make a vid?

wintry schooner
#

In the inspector, this produces a slider and a field. If I drag the slider, it saves just fine. If I manually enter a value and switch away, it resets, basically

#

Uhh, guess I could, if it's still not clear, just currently eating :P

potent sleet
#

never had that happen
sounds broken/bug . what verision of unity ?

wintry schooner
#

2022.3.0f1

potent sleet
#

not surpised 😛

wintry schooner
#

Yea, I seem to remember this not being a thing as well 🤔

potent sleet
#

3.0 been buggy for me, maybe try latest

wintry schooner
#

This whole project is becoming more and more cursed lol

#

Hm. Yea, maybe not the worst idea 🤔

potent sleet
#

Im personally still on 2021 because i dont trust 2022 yet until a few patches later 😛

wintry schooner
#

Well, I'm one of those crazy DOTS people, so...

potent sleet
#

DOTS works on 21 though no?

wintry schooner
#

Yea, some versions :P

#

I mean, I jumped on LTS because that's supposed to be where DOTS comes together

#

But here we are

#

Either way, RangeAttribute randomly breaking would be such a weird bug... I think something is just borked with this entire project, I've been getting strange ghost problems for a while now

#

Gonna update now and maybe do a full reimport or something and see where that lands. Thanks for confirming that I'm not crazy and this is not normal 👍

potent sleet
#

@wintry schooner I would try the project in a later version of unity (make sure you backup)
see if it's reproducable / fixed @wintry schooner

potent sleet
wintry schooner
#

Hm. It's fixed now 🤔

#

I refuse to believe that the version bump did it, that's just such an odd thing to break 🤔

#

Although... upgrading probably reimports as well, right? If so, that's probably what did it. Maybe this project just uncursed itself.

potent sleet
#

like adding a new script would not make it attach to gameobject

#

then i get the "All errors must be fixed before attaching script.. bla bla"

#

spoler alert: there was no error from a new script..

#

so I had to restart to make it work

heady iris
#

i'm gonna wait for another minor release or two

#

i do still have some...problems on my macbook

potent sleet
#

yea is best to wait a bit

heady iris
#

sometimes the console starts spamming "BeginWrite after EndWrite!!!!"

#

sometimes it crashes when exiting playmode

potent sleet
#

3.0 or recent ones?

#

haven't tried 3.2 but its out already

#

dont see the release notes tho oddly nvm its here today

hoary glen
#

I need a little bit of networking🤓 help. I need to make smth like a gallery that will load images from server and display them at runtime. It should get them by URL and they're indexed, like: "http://data.ikppbb.com/test-task-unity-data/pics/33.jpg". And I want it to support any amount of images. Is there any way to know the number before it starts getting the actual image data? Because I wanted it to instantiate the exact amount of images and load textures asynchronously, but for me it looks like its impossible. You either have to know the exact number of them, or send 2 requests: 1st checking if the ardress is valid and 2nd to get the texture, but what I see is that it is pointless and negotiates all the performance gained by async calls 🤔

Texture2D lastValidTexture;
    int currentIndex = 1;
    private async void Start()
    {
       
        do
        {
            lastValidTexture = await URLDataRetriever.GetTextureFromURL($"{_url}{currentIndex}.jpg");
            if (lastValidTexture == null)
                return;
            RawImage image = Instantiate(_imagePrefab, _content.transform);
            image.texture = lastValidTexture;
            currentIndex++;
        } while (lastValidTexture != null);
    }```
Thats what I came up with by far
heady iris
potent sleet
#

oh wow thats not even LTS is it?

heady iris
#

nah

#

i really wanted the 2022.x features :p

potent sleet
#

same but i tried LTS and it failed

somber nacelle
potent sleet
#

wow lots of buug fixes in 3.2 tho

potent sleet
vagrant raptor
#
{

    public Image ımage;
    public Camera cam;
    public float sensitivity = 2f; 
    public float SmoothSensivity = 2f;
    private Vector2 initialTouchPosition;
    void Update()
    {
        for (int i = 0; i < Input.touchCount; i++)
        {
            Touch touch = Input.GetTouch(i);
            if (touch.phase == TouchPhase.Began)
            {
                initialTouchPosition = touch.position;
            }
            if (touch.phase == TouchPhase.Moved)
            {
                if (!RectTransformUtility.RectangleContainsScreenPoint(ımage.rectTransform, touch.position))
                {
                    float x = (touch.position.x - initialTouchPosition.x) * sensitivity;
                    float y = (touch.position.y - initialTouchPosition.y) * sensitivity;
                    Quaternion characterrot = Quaternion.Euler(0f, x+transform.eulerAngles.y, 0f) ;
                    Quaternion camerarot = Quaternion.Euler(-y, 0f, 0f);
                    transform.rotation = Quaternion.Lerp(transform.rotation, characterrot, Time.deltaTime * SmoothSensivity);
                    cam.transform.rotation = Quaternion.Lerp(cam.transform.rotation, camerarot, Time.deltaTime * SmoothSensivity);

                }
            }
        }
    }
}```
Hello, in this code I want to rotate my character and my camera under my character, but I couldn't get a precise mechanic exactly as I wanted, can you help me?
wintry schooner
potent sky
vagrant raptor
#

thank you

graceful laurel
#

where should i post my thred requests

#

i mean help

potent sleet
#

whats a thred requests

graceful laurel
#

help request i ahhh

#

help with code

potent sleet
#

first

swift falcon
#

Oh you shouldnt be checking for Input in FixedUpdate() i also believe that you dont need Time.fixedDeltaTime on anything that has to do with movement in FixedUpdate()

#

Check for input in Update()

#

You shouldnt be doing alot of this in FixedUpdate() honestly

#

Its Physics based so theres no reason to Play audio or set animations in there. You should really only be doing stuff with anything thats Physics based IE just the Rigidbody

#

You also need to set the interpolate mode to Interpolate rather than none if you havent done so already

heady iris
#

(or whatever the physics update frequency is)

swift falcon
#

Really ? isnt that kind of redundant since FixedUpdate already runs 50 times a second ? @heady iris

#

I may be wrong tho

heady iris
#

Well, sure

#

but

#
void FixedUpdate() {
  rb.MovePosition(Vector3.right);
}
#

this will move you at 50 meters per second by default

#

probably not what you wanted

#

(also Time.deltaTime will be equal to Time.fixedDeltaTime in the context of FixedUpdate. very handy)

swift falcon
#

For 2D platformers where once you hit spikes/bottomless pits you get teleported back to the last stable ground you stood on, do games generally remember where you last stood safely or have invisible checkpoint triggers?

I can see the pros and cons of each but I feel like the former should work right?

heady iris
#

the former is easier to generalize

#

you just need a way to define a stable surface

#

probably any situation where you're on a non-moving collider and aren't being pushed by it

#

(i.e. you aren't sliding off a ledge)

swift falcon
#

Mmm yeah I imagine I'd probably do something where it checks for a wide enough open space around the player every frame

hasty haven
#

When saving keybindings in playerprefs (I have 13 right now) would it be best to just save them all as one string and parse it on read?

#

Individual feels kinda silly

swift falcon
#

Then yeah I'd probably make it so "ground" by default saves the position, but for certain grounds where I don't want it to save what would be the best way to check? A component class, tag, layer, something else?

I've had an idea for a while of making a class thats main purpose is to hold loads of tags as strings. Then I could just put it on everything I want to have tags. Only problem is calling GetComponent as it's fairly slow I think. Might be faster to make some sort of tag manager dictionary thing? Maybe I'm overcomplicating everything now

heady iris
#

i might add trigger colliders that forbid you from saving your position there

leaden ice
# swift falcon Really ? isnt that kind of redundant since FixedUpdate already runs 50 times a s...

It's absolutely not redundant. Imagine this piece of code:

float movementPerFrame = 1;
void FixedUpdate() {
  rb.MovePosition(Vector3.right * movementPerFrame);
}```
So now we're moving 1 unit every fixed update. Sure we don't need deltaTime to adjust for varying framerates. But there IS still an uncontrolled external variable here, and that is the fixed timestep. By default it's 0.02 (1/50), but you can change it. Let's say we go to the menu and change it to 0.01 (1/100) because we want more accurate collisions. Now suddenly even though the code has not changed at all, we're now moving 100 units per second instead of 50. 

It's much better to do this so you're absolutely clear in the code about how far you're moving per second:
```cs
float movementPerSecond = 50;
void FixedUpdate() {
  rb.MovePosition(Vector3.right * movementPerSecond * Time.fixedDeltaTime);
}```
Now it doesn't matter what you change the fixed timestep to in the settings, your object always moves the same realtime speed no matter what
swift falcon
#

aaahhh i see now

leaden ice
#

It's also a lot easier to think of things in terms of "per second" than "per fixed update frame"

swift falcon
#

Thank u both that actaully makes sense

heady iris
#

indeed: analyze the units

#

if something happens every frame, then the units are "per frame"

#

if you move 1 meter, then that's "1 meter per frame"

torn lotus
#

If anyone has any thoughts on my post just above that would be fantastical, I am very new to C#

leaden ice
heady iris
#

and surprise! you're actually going at like 50 meters per second

swift falcon
#

Is this a stupid idea?

public class ManagerTags : Singleton
{
    public Dictionary<string, string[]> AllTags = new Dictionary<string, string[]>();

    public void AddTag(string ID, string[] tags) => AllTags.Add(ID, tags);

    public bool CheckTag(GameObject gameObject, string tag)
    {
        if (!AllTags.TryGetValue(gameObject.GetInstanceID().ToString(), out string[] tags))
            return false;

        if (tags == null)
            return false;

        return tags.ToString().Contains(tag);
    }
}```
Anything with the Tag component can store multiple tags, and during Start() adds its tags to the ManagerTags
From then on anything can check if a gameobject has a tag by calling:

Get<ManagerTags>().CheckTag(gameObjectExample, "NotStorePosition");

Dumb or genius?
leaden ice
#

It's a fine idea in general but you could optimize it a lot and make the programming interface a lot easier to deal with

swift falcon
#

I'd love to hear your suggestions

leaden ice
# swift falcon I'd love to hear your suggestions

Just a few quick ones:

  1. Use int instead of string as the id/key type. It will be faster and use less memory (and create less garbage)
  2. Use something like a multi value dictionary instead (example here: https://github.com/SolutionsDesign/Algorithmia/blob/master/SD.Tools.Algorithmia/GeneralDataStructures/MultiValueDictionary.cs)
  3. Make extension methods for GameObject like:
public static class TagExtensions {
  public static bool HasTag(this GameObject obj, string tag) {
    ManagerTags.Instance.CheckTag(obj, tag);
  }

  public static IEnumerable<string> GetTags(this GameObject obj) {
    return ManagerTags.Instance.GetTags(obj);
  }
}```
This will let you do like `if (gameObjectExample.HasTag("NotStorePosition"))`
swift falcon
#

All great stuff thanks a ton!

leaden ice
#

Another thing to consider is you will want to figure out how to clean up destroyed objects too

#

when an object is destroyed you will probably want to remove all the tags you stored for it, or you'll have a memory leak

heady iris
#

not just because you'll be remembering tags, but also because that object can never be GC'd

#

since a reference yet remains!

leaden ice
#

basically I'd just put an OnDestroy on your Tag component

#

which will remove it from the manager

swift falcon
#

Hm alright thanks, btw so is the multidictionary faster than just storing an array?

leaden ice
#

should be the simplest approach

leaden ice
#

note that HashSet ultimately uses arrays too, but it manages the memory a bit better than if you just discard the array to resize.

swift falcon
native fable
#
        public static Vector2 GetPivot(this PolygonCollider2D collider)
        {
            Vector2[] vertices = collider.GetPath(0);

            Vector2 center = Vector2.zero;
            foreach (Vector2 vertex in vertices)
            {
                center += vertex;
            }
            center /= vertices.Length;

            return center;
        }

I want to find out the center point in such an object, I do it as in the screenshot, but somehow the center was somehow not accurately determined

heady iris
heady iris
#

sounds like you want the center of the bounding box.

#

collider.bounds ought to be relevant

steady moat
swift falcon
modern creek
#

Are there any good solutions for making a calculated property readonly & visible in the inspector? IE:

public float Speed => 1f + 1f;
heady iris
modern creek
#

I can't (don't want to) make a backing field that I set internally - I would rather this be a calculated thing

#

Specifically I have a component that has a single tween (reveal/hide) and I'd like to be able to see a property of "is animating?" without setting a backing field whenever I start/stop the tween

fervent furnace
#

you need custominspector

steady moat
modern creek
#

ay-yah

steady moat
modern creek
#

Yeah I'm trying to limit my .. attributes in this project and custom drawers. I suppose I could go that way, I was sorta hoping there were a more generic solution rather than needing to make a drawer for each instance that I'd need this

#

Especially because in this case it's just a bool

steady moat
modern creek
#

Like, this is what my current "solution" looks like and .. I hate it:

        private Tween _tween;
        [UnityReadOnly, SerializeField] private bool IsAnimating = false; 

.. any place I kill the tween:
                _tween.Kill();
                IsAnimating = false;

.. any place I start the tween:
                _tween = .... some stuff ....Play();
                IsAnimating = true;

.. and then a custom update: 
        private void Update()
        {
            if (IsAnimating && !_tween.IsActive()) IsAnimating = false;
        }
#

Yeah your solution works but I'd have to write one of those drawers for each property I wanted .. I was sorta hoping there were a generic solution that I could write an attribute for without getting too fancy with the reflection

#

I imagine I'd have to write an attribute that takes a string parameter with the name of a method, and call that or something. Not really simple and might be a bug surface

steady moat
#

Reflection is just more pratical

heady iris
steady moat
#

[Inspect] private string IsAnimating => ...;

#

The issue, is that it will be under or over the rest.

#

If you want to make it in, you will need to redraw everythings.

#

That being said, that shouldnt be hard.

quick hull
#

the other game object is not getting destroyed

#

on triggerenter

heady iris
#

you destroyed the collider

#

the object is now colliderless

quick hull
#

oh

#

how would i destroy the gameobject

heady iris
#

well, you've probably gotten the game object from a component before

#

in fact, that's what gameObject.tag is doing

#

every component has a .gameObject property

quick hull
#

oh

#

ok

#

other.gameobject

heady iris
#

ya

chilly beacon
#

https://www.youtube.com/watch?v=waEsGu--9P8&t=0s

guys i am trying to add a pathfinding algorythm to my game and i am following this video but i dont understand what he is doing, he me made a grid class in the beginning of the video do i need to make a grid class i mean i have a mapGenScript which generates a random map use procedural gen and i use a multidimensional array there i dont if i even need the grid class he does could someone explain to me whats going on here?

✅ Get the Project files and Utilities at https://cmonkey.co/gridsystem
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
Let's make a Grid System that we can use to split our World into various Grid Cells.
Then we can use that to make a Heatmap or a Pathfinding Map with avoid/desire areas or a Building Grid System.

Complete Grid ...

▶ Play video
swift falcon
#

Anyone know why these two instanceIDs are different?

private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.TryGetComponent(out ContactDamage contact))
        {
            Debug.Log(contact.gameObject.GetInstanceID()); // 1
        }
    }

public class Tags : MonoBehaviour
{
    private void Start()
    {
        Debug.Log(GetInstanceID()); // 2
    }
}```

The gameobject has two main components, ContactDamage and Tags
How could these instanceIDs be different even though it's the same gameobject?
heady iris
#

beacuse GetInstanceID() is a method of UnityEngine.Object

#

you can call it on anything that's a unity object

#

GameObject and MonoBehaviour are both objects

swift falcon
#

Ah I see whoops

heady iris
#

GetInstanceID() down there is being invoked on your monobehaviour

#

up top it's on a game object

hollow hound
#

What is the best practices regarding extracting methods?
I have pretty big class with long functions in it. I divided this functions to multiple ones, but where should I store them?
Static helper class? Maybe non-static class which I initialise with parameters to avoid passing the same variables to all its functions? Or maybe I shouldn't use another class at all and there are better approach to this?

gray mural
#

probably you should consider using #region then

steady moat
#

You should try to follow the SOLID principle.

hollow hound
steady moat
hollow hound
# steady moat You will need to be more specific.

Checking collisions, mapping them, filtering collisions, caching needed components of collided objects, invoking events for collision, damage calculation for each collided object, invoking damage events, applying damage, finding position for spawn another objectm instantiating this object, etc.
It's not like I am doing, for example, "applying damage" in this function, I am just calling a couple of functions from corresponding class, but still there is a lot of code in this class, so I want to know where should I extract new functions.

hollow hound
steady moat
gray mural
steady moat
#

There is a lot of function that are variation of others

gray mural
steady moat
hollow hound
#

Hah, no

steady moat
#

However, I cannot know because I do not see anything.

#

We can even start with 1 function.

gray mural
#

@hollow hound probably namespaces should help you somehow?

leaden ice
#

arrays can't be resized

steady moat
#

Because a list would behave the same.

hollow hound
leaden ice
#

The hashset also has the advantage of not allowing duplicates

steady moat
heady iris
#

hash sets and maps handle collisions.

#

er, hash maps do

#

i would expect the same from hashsets

steady moat
#

Pretty sure Hashset does not.

#

Might be wrong.

hollow hound
# steady moat It depends on what you do.

It looks something like this:

void HandleCollisions(...){
  var collidersInfo = GetCollidersInfo(...)
  foreach (var colliderInfo in collidersInfo) ProcessCollision(...)
}

MyClass[] GetCollidersInfo(...){
  // dozens lines of code
}

void ProcessCollision(...){
  // dozens lines of code
  ProcessOnHitLogic(...)
}

void ProcessOnHitLogic(...){
  // dozens lines of code
}

The question is, where should I put this GetCollidersInfo, ProcessCollision and ProcessOnHitLogic?
Their logic is specific for this class, they are called only from one place each.

zealous goblet
#

Hey guys, I am developing a mobile 2D game and for some reason when I use unity remote 5 on my IOS and play the game, it's getting low fps and very blurry/pixelated. I have tried to put the spirits on the "point (no filter)" mode and fixed so the resolution matches the screen, what could be the problem?

steady moat
#

Have one component that does the collision processing, while other listen to this one.

hollow hound
steady moat
#

At least, I would expect.

#

However, because I do not know nor see your code, I cannot know.

mystic yoke
#

So you're just trying to organize your class so it's cleaner?

hollow hound
native fable
mystic yoke
#

Make your class a partial, and split it into multiple files

steady moat
#

Oh god, please do not make partial.

swift falcon
#
  1. Does this work in builds of the game?
  2. Is this a terrible idea?
    BoxCollider2D _col;

    private void OnValidate()
    {
        _col = GetComponent<BoxCollider2D>();
    }```
heady iris
#

i have since factored out big chunks into a state machine

heady iris
mystic yoke
steady moat
native fable
swift falcon
#

My idea here is that all components are assigned in the editor so:
I don't have to assign them myself with dragging and dropping (SerializeField method)
It reduces time to load scenes and improves performance (GetComponent method)

heady iris
#

and also nothing to do with performance

leaden ice
steady moat
mystic yoke
#

I feel like unity should also provide a center of mass for colliders 🤔

leaden ice
#

so that assignment will not make it into the build

somber nacelle
swift falcon
#

If I do [SerializeField] will it save?

leaden ice
#

yes

swift falcon
#

Bad idea though?

mystic yoke
#

Not onvalidate

steady moat
mystic yoke
#

Or is it just Reset, I can never remember

#

Oh boxfriend beat me to the punch

vagrant cradle
#

!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.

gray mural
#

and yes, late reply, sorry

somber nacelle
# vagrant cradle !code

i gotta ask, why do you use that command in this channel just to then post your code in another channel? you know you can use the command in the channel you intended to post your code in. or even just bookmark one of the bin sites since you use the command so frequently

gray mural
#

dividing the function means making it virtual

hollow hound
# steady moat What are those events.

Events like "onHitboxCollisionEnterStart", "onFrameCollidersEnter" that other classes listens to. It's pretty complex system, and I don't think I can explain it in reasonable time. In short, this is class of weaopn behaviour. HandleCollisions calls GetCollidersInfo that filters and caches colliders. ProcessCollision invokes multiple events for triggers, calculations and damage receiving, it also calls ProcessOnHitLogic that handles spawning another entities with more logic.
I wonder where should I store those functions, because this class is already 350 lines long and growing quickly

vagrant cradle
steady moat
hollow hound
# steady moat - 350 lines is nothing - Use component to divide the behavior - Add intermediate...

Why component? I don't want instantiate it or something, it's pure logic in this functions.
Where should I store Hit, Filter, Triggers, Actions? In one class? In multiple classes? Non-statiс classes that are initialising with parameters or static in functions of which I should pass same/similar parameters?
There is always a limit of "Single Responsibility". Or should I make a new class for all this functions?

steady moat
# hollow hound Why component? I don't want instantiate it or something, it's pure logic in this...

I do not know because I am not in your project. You are asking question that I are situational base on what you are actually doing.

  • Component does not need to be instantiate at runtime.
  • It depends on what you currently have. They could be in a separate class.
  • Single Responsability is single responsability. You described multiple responsibility in what you are saying, so I guess it might have not been correctly applied.

However, I cannot know for sure what can be modified without seeing actual code.

hollow hound
#

Ok, thanks for the hints

rancid pollen
#

hi, is there any difference between ObjectPool.Clear() and .Dispose()? just trying to confirm if the docs are right, 'cause they have the exact same description

rancid pollen
#

i see, thanks

somber nacelle
#

the reason both methods exist seems to be because of the two interfaces. It implements IDisposable so that's why it has the Dispose method, but the IObjectPool<T> interface has a Clear method which is better named for what its purpose is

heady iris
#

ah, it does? i went looking but didn't see IDisposable mentioned

#

oh yeah, there it is in the reference

#

it's not mentioned in the unity docs

somber nacelle
#

yeah i noticed that, kind of odd that it isn't mentioned there

#

but there's plenty of objects with undocumented behavior

terse raven
#

hi

#

oh wait this isnt general

#

thais is code general

somber nacelle
terse raven
#

sorry guys\

#

i must get going

#

toodles

hollow hound
#

There is no way I can implicitly inherit a constructor, right?
Like:

    public class A
    {
        public A(int num)
        {
        }
    }

    public class B : A
    {
    }

It won't work because I have to explicitly declare public B(int num) : base(num){}
Is there a way to avoid this? If not, I wonder why is it made this way.
Like when I create B, it can check constructors with given params in child and parent class, what am i missing?

cold parrot
hollow hound
cold parrot
#

its made so you can constrain ctor options in derived classes

hollow hound
cold parrot
#

yes, or different signatures and defaults you might pass on to the base

vestal crest
#

Hey, I invoke an action when a node selected on a grid.
I have 3 situations for now but i may have more in the future.
If I selected a building from the UI i should build it.
If i didnt select a building and theres a unit on the node i should select the unit and display it on UI
If i didnt select a building ad theres no unit on the node then i just return or do something else.

How can i build this without breaking solid principles and being able to extend it later on

cold parrot
#

e.g. you can do public Foo() : base(default) {} to add a parameterless ctor or private Foo() {} to remove the parameterless ctor that may be on the base

lethal tusk
#

how can I make UI looks the same on all devices?
In Canves settings I use Scale with screen size, but no idae what should i use for Reference resolution. My game is 9:16 on mobile

vagrant blade
#

The reference resolution matters for your imported art, so you can match the scale.

#

If this means nothing to you, then just use a common resolution like 1920*1080 and keep it consistent across all your canvases.

spiral cedar
#

Has anyone had this editor draw call issue where serialized classes in lists or dictionaries are not changing the size of the editor elements?

#

Seems to happen to all my serialized classes in 2021

lethal tusk
vagrant blade
#

Yes, so you make the UI how you want it to be.

potent sleet
vagrant blade
#

If you knew the scale your assets were made in, you would use that resolution and choose the Set Native Size button on things like images.

somber nacelle
weary rose
#

does anyone know how I can make it so that when i switch cameras, the player doesn't doesn't like whip around? What i mean is, when the player is in the free look camera mode and the camera and player model are facing in oposite directions. then when the player switches to the backview, the player model faces where the free look camera was facing before

dusk apex
potent sleet
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.

weary rose
#

my code is to long to do inline

somber nacelle
#

if only there were instructions for large code blocks

lean sail
#

funny too, because inline isnt even the first part of that command

dusk apex
weary rose
#

there

#

i think i did it right

potent sleet
#

it learns

weary rose
potent sleet
#

so you want the rotation to be gradual ?

weary rose
#

for example, if the player is in the freelook camera angle and the camera and player are facing opposite directions. Then if the player switches to the combat camera, the combat camera should look to wherever the freelook cmaera was looking and the player should face that way too

potent sleet
weary rose
#

no

#

here

#

let me record a vid really quick

potent sleet
#

thought you meant the rotation

#

I see

weary rose
#

👍

#

its kind of hard to explain

potent sleet
#

i get it

weary rose
#

cool

potent sleet
weary rose
#

wdym virtual cam

potent sleet
#

what mode rather

weary rose
#

?

#

the freelook camera is basic and the combat is combat

#

if thats what you're asking

potent sleet
#

no like show the virtual cam cinemachine component

#

combat camera

#

you want it to match the previous rotation from freelook yes?

weary rose
#

yeah

potent sleet
#

it should be as easy as storing the camera's rotation before the switch them rotate with the variable you stored

sweet raft
#

If I set a string to public (or serialize it to show up in the inspector), how can I put line breaks in the field in the inspector?

potent sleet
#

but it matters which virtual camera mode you have set for Look/ Body

#

some mode lock rotation

weary rose
#

im a still a little confused on what you mean by the virutal part

potent sleet
weary rose
#

yeah

potent sleet
#

do you not know what a virtual camera is ?

weary rose
#

not really

potent sleet
#

oh..can you screenshot the inspector for combat camera

weary rose
#

do you want me to send you this

lean sail
sweet raft
weary rose
#

@potent sleet

#

is that it

potent sleet
weary rose
#

cool

potent sleet
#

now, you see the target

#

Look At

weary rose
#

the look at

#

yeah

potent sleet
#

you have rotate that with camera when its in free look

weary rose
#

does that have to do with code

potent sleet
#

yeah probably

weary rose
#

how would I do that?

potent sleet
#

hmm maybe
CombatLookAt.transform.rotation = Camera.main.rotation

weary rose
#

is it simmilar to this? /rotate orientation
Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
orientation.forward = viewDir.normalized;

potent sleet
#

oh wait you gotta move it too

#

im trying to remember how freelook works

weary rose
potent sleet
potent sleet
#

yes show this object in the scene

weary rose
potent sleet
# weary rose

can you make video of it in playmode , put game tab in side by side and lemme see where it goes in playmode

weary rose
#

sure

#

give me a sec

potent sleet
weary rose
#

orientation

potent sleet
#

for comabat look at you should put the target where the player is basically and rotation should be the same from the freelook camera before switching

#

store the rotation in a quaterion

weary rose
#

huh?

potent sleet
#

this way you can preserve rotation

#

when you switch from free look to look at you pass the rotation of your current camera to that CombatLookAt

#

then rotate player as well with that rotation

weary rose
#

is there any docs that can help me do that

#

because I have no idea how to do any of that

potent sleet
#

there are methods to do this but this isn't a docs for this

#

its specific to your situation

#

thats how coding works 😛

#

you can probably find a tutorial which already does this just by making this camera system

#

its very common anyway, im sure you inevertly bump into the correct code or find it on unity answers

weary rose
#

mb

vague jolt
#
   void Update()
    {
        if(cableUsed != 0)
        {

            if (Input.GetMouseButtonDown(0) && qDetection.hoveringGameObject!=null)
            {
                structure1 = qDetection.hoveringGameObject;
            }

            if (structure1 != null)
            {
                if (!cableInstantiated)
                {
                    cable = new GameObject("cable");
                    lineRenderer = cable.AddComponent<LineRenderer>();
                    if(cableUsed == 2)
                    {
                        lineRenderer.material = green;
                    }else if(cableUsed == 1)
                    {
                        lineRenderer.material = red;
                    }
                    lineRenderer.startWidth = 0.05f;
                    lineRenderer.endWidth = 0.05f;
                    cableInstantiated = true;
                }

                if(Input.GetMouseButtonDown(0) && qDetection.hoveringGameObject != null)
                {
                    structure2 = qDetection.hoveringGameObject;
                    lineRenderer.SetPosition(0, new Vector3(structure1.transform.position.x, structure1.transform.position.y, -1));
                    lineRenderer.SetPosition(1, new Vector3(structure2.transform.position.x, structure2.transform.position.y, -1));
                    structure1 = structure2;
                    structure2 = null;
                    cableInstantiated = false;
                }
                else
                {
                    lineRenderer.SetPosition(0, new Vector3(structure1.transform.position.x, structure1.transform.position.y, -1));
                    Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                    lineRenderer.SetPosition(1, new Vector3(mousePosition.x, mousePosition.y, -1));
                }
            }
        }
    }

I am using this code to place lines between game object

#

but when i press on the second game objct the lines stops getting rendred

weary rose
#

found a tutorial

#

In this video, we’re going to look at how we can set up a third-person camera using the new Aiming Rig of Cinemachine 2.6, and how we can use Impulse Propagation and Blending to create additional gameplay functionality for our camera controller.

Download this project here!
https://on.unity.com/36nVNzt

Learn more about Cinemachine 2.6 here!
htt...

▶ Play video
vague jolt
potent sleet
swift falcon
#

What values does Unity put into a web request User-Agents header?

#

@leaden ice I'm in a position where I can't do that lmao

heady iris
#

y

#

make a RequestBin and look at the request

#

or you can probably just print out the request in the console

swift falcon
heady iris
#

i don't see why you can't Try It And See

swift falcon
#

honestly I don't know how to do this completely :x

#

a RequestBin?

#

I'll investigate trying to print to console if I can

#

Okay we do have UnityWebRequest.GetRequestHeader so I'll use that

vague jolt
#

how do i declare a function that uses a list as a parameter ?

#

void delete(<GameObject> cables) this does not work

#

i am stupid

#

solved

swift falcon
#

So since user-agent is not a custom header it returns Null to me

swift falcon
frigid hollow
#

spanish?

potent sleet
frigid hollow
#

:c

#

Is there a server in Spanish?

potent sleet
#

google around I'm sure you'll find one, search reddit too

ionic grove
quartz folio
ionic grove
vagrant blade
#

The user guide should give you an example, and there should be a scene with it as well.

#

But quickly looking at some old code project, it looks like you need to implement the IMoverController interface, and also give your object the PhysicsMover component(?)

quick hull
#

why does the score turhn -1

#

after only one collison

#

the intial lives is set to 3

potent sleet
#

more context i don understand

quick hull
#

so basically

#

the lives are set to 3

potent sleet
#

you should label your debugs nbtw lol

#

Debug.Log($"Lives:{manager.lives}")

quick hull
#

and ontriggerneter if the shape is wrong it should -1

#

but instead on the first wrong it goes from 3 to -1

potent sleet
quick hull
#

in the last else statement?

potent sleet
quick hull
#

ok i think ik the problem

potent sleet
#

i edited lol

quick hull
#

how would u destroy a script from instantiated object

#

i tried this

#

but it doesnt work

potent sleet
quick hull
#

i want to destroy the scorehandler

#

script

potent sleet
#

component goes in the T

#

GetComponent<T>()

#

replace T with scorehandler script or w/e

quick hull
#

oh ok

graceful rampart
#

hey so this seems very basic but i cant seem to get it right im trying to make this object rotate and always face the character which is what is happening but when i start the game the position and rotation of the object is completely messed up, any reason why?

mellow sigil
graceful rampart
#

could you explain what i did wrong

mellow sigil
#

The article I linked explains it in detail

graceful rampart
#

im reading it i dont understand what I did wrong

#

i have 2 points and a speed in between getting to the points

mellow sigil
#

Right, and that's not how lerp works

graceful rampart
#

ok please help me and tell me what i am doing that doesnt work

#

because right now looking at the article i dont see my mistake

#

or undestand it however

mellow sigil
#

You didn't read the whole article in 2 minutes

graceful rampart
#

ok

#

a better question, would i use lerp for this scenario

#

based on my learning, no

#

and is my mistake the problem of the rotation

prime sinew
#

But yes 2 things wrong with your lerp. Improper 3rd parameter

#

And your start parameter is always updating. It should be cached

graceful rampart
#

ok how would I replace the time.deltaTime slot bc i understand that wont ever make it to what the desired position

#

and how would I replace the first paramater to the position of the game object

prime sinew
prime sinew
graceful rampart
#

you dont need to keep stating it im reading it

prime sinew
#

You asked,I answered

prime sinew
#

Or RotateTowards

#

I forget the difference

graceful rampart
#

trying to use LookAt it works the same but the rotation is still being weird

#

like the game object is still snapping to a different position

prime sinew
#

Can't help unless you show code

graceful rampart
#

no im just rly stupid i fixed it

#

sry for all the confusion, I do understand Lerp correctly now tho so thank you both!

prime sinew
#

I also just remembered you can set the direction an object is facing by just doing something like this

#

RotatingObject.transform.forward = targetVector

#

@graceful rampart

#

Assuming the forward axis is the front

graceful rampart
#

good to know Ill keep messing with it, appreciate it

prime sinew
#

Try again, and show your attempt next time

sleek bough
#

You need to fix all errors first for project to compile.

#

Also don't cross-post

sharp root
#

Yo

#

How do i reference a bool from another script

#

public bool Vibration;

sleek bough
#

Consider going through Unity courses to learn basics. links are in the pins

knotty sun
#

screenshot the script you are trying to drag

sleek bough
#

@swift falcon You have animator selected. You can add scripts only on game objects

knotty sun
#

screenshot the script in the project window

#

do you have 2 classes Player and player in one file?

#

that shows that there are 2 different classes in your script fioe. One called Player and one called player

#

you can only have 1 monobehaviour class in a script file

#

yes, i'm guessing Player is the one to delete

frozen ermine
#

And then change class player to class Player

native fable
#

hello everyone, I wrote this method for calculating the intersection points of splines, and there was such a problem that sometimes it gives out several points instead of one at the intersections due to the fact that the distance is less than 0.01 for several points at once. Maybe there is a way to fix this?

knotty sun
#

no, the complete definition for class Player

#

from public class Player to public class player but not including the last line

ruby cloak
#

Hi, I'm making a Race master 3d Like which in which a car basically follows a spline to follow a path but the problem is I need to give user a little control as is in original game where player can swipe and change the direction of the car while staying on the spline path and in very few cases leaves the path is there any suggestion ?

Things I have tried:
Made a Empty gameobject and made it follow spline and made the car child to that gameobject. (Didn't work as car deviates from the path more than epected or starts doing 360 flips)

steady moat
haughty zephyr
#

Does anyone have experience with the Unity UDP package? I've imported it into my project today and it immediately caused duplicate pre-compiled library issues. It seems to be clashing with the Unity In-App Purchasing plugin? 😦

#

OK, so having removed the package via Package Manager and reinstalling it. The errors are gone, that's worrying. 🙂

sharp root
#

Why am i getting an error on this line?

#

if (vibscript.Vibration == true) { Handheld.Vibrate(); }

#

Object reference not set to an instance of an object

#

I have referenced it public Vibrations vibscript;

#

And this is my other script

#

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

public class Vibrations : MonoBehaviour
{
public bool Vibration;

public void Start()
{
    Vibration = true;
    DontDestroyOnLoad(gameObject);
}

public void VibrationsSave()
{
    Vibration = !Vibration;
}

}
`

#

🤨

knotty sun
#

and filled the reference in the inspector?

sharp root
#

What do you mean

#

I made a gameobject and attached the vibrations script to it

#

if youre asking that

knotty sun
#

and now you need to drag/drop that into vibscript in it's inspector

sharp root
#

But the vibscript is just a reference to the Vibrations script

knotty sun
#

not untill you fill it with something it is not

#

atm it is empty (null)

steady moat
sharp root
knotty sun
sharp root
#

Its quite big

knotty sun
#

sorry, the inspector of the gameobject which is using the script containing that line

sharp root
#

Oh

#

I get what you mean

#

But the object where i need to attach the vibscript is a prefab

knotty sun
#

then you cannot do that, prefabs cannot directly reference scene objects

sharp root
#

Dammit

prime sinew
#

I'll see if I can help

sharp root
#

Well

#

So i have a settings menu , which is in the main menu scene. There i have a toggle that switches the vibration of the Ball when it hits the hoop(On or off). I have this script

#

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

public class Vibrations : MonoBehaviour
{
public bool Vibration;

public void Start()
{
    Vibration = true;
    DontDestroyOnLoad(gameObject);
}

public void VibrationsSave()
{
    Vibration = !Vibration;
}

}
`

#

This void VibrationsSave attached to the toggle

#

But

ashen yoke
#

any vs extensions that generates event handler method on += ?

sharp root
#

I have a Ball gameobject which is a prefab and it has a ballcontrol script which is quite big to post but heres the main thing

prime sinew
#

Finally

sharp root
#

When the ball hits the hoop

#

`void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name == "WinTrigger")
{

        SceneChangeTracker.counter ++;
        GameObject.Destroy(wintrig);
        if (vibscript.Vibration == true)
        {
            Handheld.Vibrate();
        }
        WinMenu.SetActive(true);
        menubutton.SetActive(false);
        celebration.Play();
    }`
#

Object reference not set to an instance of an object

#

And i cant set it cuz its a prefab

#

Ya

prime sinew
#

No I meant when you rephrase your question you just get to the point..

sharp root
#

Well

#

Sorry

ashen yoke
prime sinew
#

Now you're not even telling me what's causing the null ref

knotty sun
prime sinew
#

I don't have time sorry

#

Read this and see if it'll help

sharp root
#

But thanks

ashen yoke
prime sinew
sharp root
prime sinew
#

Nevermind

sharp root
#

I have read it before

ashen yoke
knotty sun
#

@sharp root So the basic solution is
once you have instantiated the prefab you need to get a reference to the Vibrations script and fill vibscript
So can you add a vibscript reference to the script that instantiates?

prime sinew
knotty sun
sharp root
#

Yes

knotty sun
#

great, so add this

public Vibrations vibscript;

to that script then screenshot the inspector of it's gameobject

sharp root
#

Wait sorry

#

I cant add a vibscript reference

knotty sun
#

why not

sharp root
#

Its 2 seperate scenes and the other object is a prefab as i have mentioned

knotty sun
#

you only ever have 1 Vibrations script active, correct?

sharp root
#

yes i do

#

The Vibrations script itself

knotty sun
#

ok so in the Vibrations script add

public static Vibrations vibscript;

and in the Start method

vibscript = this;
sharp root
#

Ok i have

knotty sun
#

now in your Ball script in the start method add

vibscript = Vibrations.vibscript;
sharp root
#

Ur a genious

#

it works

royal pulsar
#
using UnityEngine;
using UnityEngine.Events;

public class ShootHitscan : MonoBehaviour
{
    [SerializeField] private UnityEvent shotFired;
    [SerializeField] private Transform firePoint;
    [SerializeField] private float range = 10f;
    [SerializeField] private PlayerInput playerInput;
    [SerializeField] private Hit hit;
    private Recoil recoil;

    private void Awake()
    {
        recoil = GetComponent<Recoil>();
    }

    private void OnEnable()
    {
        playerInput.onClickEvent += Shoot;
    }

    private void OnDisable()
    {
        playerInput.onClickEvent -= Shoot;
    }

    public void Shoot()
    {
        // Check if recoil period is over
        if (!recoil.InRecoil)
        {
            // Shoot raycast and return hit object (or null)
            RaycastHit2D hit = Physics2D.Raycast(firePoint.position, firePoint.right, range);

            // If the ray hit an object, check if the object is Hittable
            if (hit)
            {
                GameObject hitObject = hit.transform.gameObject;
                TryHitObject(hitObject);
            }

            // Enable recoil period
            recoil.InRecoil = true;

            shotFired.Invoke();
        }
    }

    void TryHitObject(GameObject objectToHit)
    {
        if (objectToHit.TryGetComponent(out Hittable hittableObject))
        {
            hit.knockbackSource = transform.position;
            hittableObject.TakeHit(hit);
        }
    }
}

I have this class which I want to make more generic. Right now it shoots a raycast, checks if it hits, then applies damage. However, looking back, the responsibility of this class should only be to shoot something (be it a raycast, or a projectile, or a mine, etc). Is this a good opportunity to make an interface?

leaden ice
#

Turn on Rigidbody interpolation

#

Also you'd have to show how the up and down movement works

#

Because MovePosition is not generally compatible with any other type of movement simultaneously

#

Yeah no

#

You can't mix velocity and MovePosition

#

Not really seeing the issue tbh

#

It seems smooth in both videos

thin aurora
#

This video should be pinned here: https://www.youtube.com/watch?v=fmbYlYU7z9Y
Actually very informative and useful.

Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
Show your Support & Get Exclusive Benefits on Patreon (Including Access to tall tutorial Source Files + Code) - https://www.patreon.com/sasquatchbgames
Wishlist Veil of Maia! - https://store.steampowered.com/app/1948230/Veil_of_Maia/
Wishlist Samurado!
https://store.steampowered...

▶ Play video
thin aurora
#

Rip, it was already posted

steady moat
#

Some of those tips are not even Unity specific.

thin aurora
#

Despite that, very useful to use whilst developing

#

But yeah, I noticed that

graceful blade
#

Is it possible to wait for end of frame in an async method? I would like to play an animation and let my Task delay for the length of the animation, however it appears that I must wait a single frame before using GetCurrentAnimatorClipInfo to get the correct length.

heady iris
#

not sure if this will help you, but LateUpdate runs after animation.

graceful blade
#

I usually like to keep things in scope, so it's not everywhere, however, if there's no other way, I guess that's an option.
Specifically I'm trying to make an async method that I can await to play the animation till it completes

swift falcon
#

Is there a way I can reference an unknown component and then enable/disable it from code?
Something like this:

[SerializeField] Component[] _enabled;

    public void TimeChanged(bool forward)
    {
        foreach (Behaviour b in _enabled)
        {
            b.enabled = forward; // COMPILER ERROR, Component does not have "enabled" :(
        }
    }```
leaden ice
#

Make it a Behaviour array

swift falcon
#

I imagine this is due to the fact some components can't be disabled but is there any subclass or anything?

leaden ice
#

You're already using it in your example partially, yes

#

the subclass is Behaviour

swift falcon
#

Ah right I tried that as well but I wasn't able to assign SpriteRenderer to it for some reason

leaden ice
#

some components are not Behaviours though

heady iris
#

Because that's not a Behaviour!

leaden ice
#

Renderers being one example

heady iris
#

Bit of a headache, innit

leaden ice
#

Colliders being another

heady iris
#

I just did separate lists when I was in a similar situation

swift falcon
#

Colliders and renderers are like the two things I want lol

steady moat
leaden ice
#

you could do this:

Component[] components;

foreach (Component c in components) {
  if (c is Renderer r) r.enabled = true;
  else if (c is Collider col) col.enabled = true;
  else if (c is Behaviour b) b.enabled = true;
  else { // no }
}```
swift falcon
#

Hm alright thanks

graceful blade
rain warren
#

Hi there, I want to do smooth NPC movement based on the new splines package. Basically I calculate path with navmesh, and then I'm creating spline based on path corners. The problem is that knots positions are local and therefore when I move the agent spline is moving as well, and It's crucial that spline component is on the NPC game object. Is there any way to switch spline to global space, or some kind of not tedious workaround to this?

#

Here is my path generation code:

#
 {
        NavMesh.CalculatePath(transform.position, _destination.position, _agent.areaMask, _path);
        _pathCorners = _path.corners;
        _spline.Clear();

        for (int i = 0; i < _pathCorners.Length; i++)
        {
            BezierKnot bezierKnot = new BezierKnot();
            bezierKnot.Position = _pathCorners[i] - transform.position;
            _spline.Add(bezierKnot);
        }
        _spline.SetTangentMode(TangentMode.AutoSmooth);
    }```
heady iris
#

you could just deparent the object with the spline on it 🤔

#

I think I did that once

#

ah, but you said it must remain on there

#

One option would be to convert the world-space points back into the local space of the object

#

but that would make the editor visuals very confusing

#

the spline would be moving around

rain warren
#

yeah, and this is exactly what I want to avoid

#

or maybe I should do some kind of spline manager placed in global (0,0,0), and when one particular npc creates spline it will be added to list, and npc got reference to index on that list. And making one object for all npc's should not be such a big deal

native fable
#

Does anyone know how to call this generation from code?

potent sleet
remote canopy
gray mural
#

Does anyone know how to activate TMP_Text without typing anything into it? Probably just null, string.Empty or \0

gray mural
native fable
leaden ice
gray mural
# leaden ice what are you trying to accomplish

I am trying this method to work probably at the start (when nothing is typed yet)

private void AlignCaret()
{
    if (_textInfo.lineCount == 0)
        _textInfo.lineCount = 1; // lineCount is 1, but lineExtents is still Vector3.zero

    TMP_LineInfo currentLine = _textInfo.lineInfo[_textInfo.lineCount - 1];

    TMP_CharacterInfo charInfo = _textInfo.characterInfo[currentLine.lastCharacterIndex];

    Extents extents = currentLine.lineExtents;

    float middleX = (text.Length > 0) ? charInfo.xAdvance : extents.min.x;
    float middleY = (extents.min.y + extents.max.y) / 2f;

    caret.position = textComponent.transform.TransformPoint(new(middleX, middleY));

    print(middleX + "  " + middleY);
}
#

that's custom caret

leaden ice
#

Are you making your own input field?

gray mural
#

trying to make probably

leaden ice
#

What's wrong with the built in one?

potent sleet
gray mural
#

I need to make infinite Input Field

#

that is possible to work normaly with at least 100k characters in default conditions

#

I have made typing system and caret already, but it is not activated until TMP_Text has some characters in it

leaden ice
gray mural
#

first in this case

#

and I cannot access it's beginning

#

when TMP_Text does not have any characters

native fable
civic berry
#

how do i change mouse sensitivity with a script. im making a 1st person shooter

versed marsh
#

for some reason the emissive material isnt showing up in my camera view, but is in the scene view. My guess is because my camera is so far away, but im not entirely sure. I'm using URP

#

Left is scene view, right is game view

somber nacelle
native fable
fluid forge
#

Hello everyone !

I'm curious to know. Does a tool / package exist to parse the Unity.txt log in a nice way ?

I read my log file from my build. But it's visually not appealing and parsed so.

ebon plinth
#

not sure where to ask this but does anyone know where I can find all scripts that I've created in a project. There's some under assets but that's not all the one's I've used and I'd rather not search for them every time

heady iris
#

you could search for t:script to search for every script asset

lean sail
#

That's what I did at least, saved myself money at the cost of my sanity

fluid forge
#

Yes ! I searched for some but didn't find any after runtime.
Basically having a logger in the game is good. But I need to parse the file from the runtime build
If you have a good package to recommend I'm all ears !

lean sail
#

And any language pretty much

fluid forge
#

Yes ! I already did a small one in JS so it can be shared around. I hesitated doing it directly in Unity
Even if it's paid, no logger is doing that on the store right now I feel !

lean sail
fluid forge
#

Odin as in the serializer ? Oo.

lean sail
#

actually idk if im remembering wrong, might not be odin. Quantum was shown in a networking tutorial where the guy was building to run multiplayer and needed it

#

i barely ever look at these paid packages tbh, it really shouldnt be hard to build yourself if all you want is file logging to screen

fluid forge
#

Oh I see. But quantum is a console not à log parser

#

Yes you're right. Just wanted to save a bit of work.

lean sail
#

from how i saw it used, it does print the logs to console

#

but yea the reason its expensive is not because of this basic feature, you can add commands and view a lot of other stuff

heady iris
#

i would just write to a different file

#

get the directory from that path, then write your file there

somber nacelle
#

i personally just use serilog and wrote a sink for it that just fires an event when a log is sent so that i can do whatever i need to in game with it, like hook it up to an in-scene text box or something

lean sail
#

oh maybe im misunderstanding what this was for 🤔

rigid island
#

is it possible to use a MonoBehaviour as key to dictionary ?

GetHashCode() and Equals() , are they necessary to override in this case?

heady iris
#

nothing special is required.

rigid island
#

awesome, thanks!

swift falcon
#

Hey everyone im having trouble with a character selector while using addressables im really really confused

#

Basically the system i have in place is you select a skin and hair which are buttons. OnClick gives you a string which is the addressables Address i put that address into a class Serialize the class before a scene change and then Deserialize it OnSceneLoad() and even though the address im getting is correct it still gives me the wrong skin and hair and i for the life of me cannot figure out why its quite a bit of code if anyone is interested in helping

main tree
#

Hi, if there's someone who is interested with PUN (Photon) can you help me?

GetComponent<PhotonView>().Owner.NickName = "arda";
The only thing I write is this, but it gives NullReferenceExpection error.

I checked it with Debug.Log() and I found PhotonView is not null but owner is.
What can I do?

leaden ice
main tree
ebon plinth
heady iris
#

put your scripts in a folder.

main tree
ebon plinth
#

putting things in a folder is only for organization and wont affect heirchy or anything right?

#

sorry about the noob questions I'm pretty new

leaden ice
#

PhotonNetwork.PlayerList

leaden ice
#

In project window?

ebon plinth
#

erm just to stay organized

#

I think the asset window

leaden ice
leaden ice
#

then ask the question again

heady iris
#

the Hierarchy displays objects that are in the current scene.

#

this has nothing to do with the hierarchy.

ebon plinth
#

alrighty thank you

heady iris
#

you can move assets around as much as you want without having any problems

#

just do it in Unity.

#

or move the .meta files with the actual files

main tree
heady iris
#

if you don't keep the .meta files together, Unity will think you deleted Assets/MyScript.cs and created Assets/Scripts/MyScript.cs

#

neat trick: add a compile error so that unity can't recompile, then move your scripts around within unity

#

it'll be a lot faster than way

#

(otherwise, it will recompile every time you move a script asset)

ebon plinth
#

that sounds a bit advanced for me idek what a meta file is but I'll keep it in mind if I do make a folder

heady iris
#

you will see lots of .meta files

#

make a folder. select all of your scripts and put them in it.

ebon plinth
#

along with the .meta files too yea?

#

aha found the folder

heady iris
#

"found the folder"?

heady iris
#

That way, you don't even have to worry about it.

ebon plinth
#

oh I was going to move the meta files and the script files together and manually create a folder called "scripts" in explorer

heady iris
#

that would work, yes

#

also, are you using version control?

#

if not, do that before you start rearranging everything

#

in case you, say, decide to move the files in Explorer and don't move the .meta files

ebon plinth
#

I just did it in unity looks like everything works

#

thank u

lavish ridge
#

How could I run a script only after all OnCollisionXXs have been run for the "normal tick", or frame?

I saw on the docs you're supposed to use PlayerLoop to do this, but they didn't go into very much detail about how to use it or how it works.

somber nacelle
#

you can use a coroutine and yield WaitForFixedUpdate that happens just after collision messages during the physics loop

lavish ridge
#

Thx!

somber nacelle
timber locust
#

Im working on a Udemy class but I'd like some company since I easily lose focus/get offtask. Is there a particular voice channel that I could use to stream my work?

somber nacelle
earnest gazelle
#

How can I set readable/writable setting for a runtime texture?
I see it is false by default.

To toggle this, use the Read/Write Enabled setting in the Texture Import Settings, or set TextureImporter. isReadable. By default, this is true when you create a texture from a script. Note: Readable textures use more memory than non-readable textures.
heady iris
#

well, that documentation says that it's true by default for a texture you create from a script

somber nacelle
earnest gazelle
#

I create them and save them

#

I want them to be readable/writable but they are not.

somber nacelle
#

wanna provide relevant code so nobody has to make assumptions about what you may or may not be doing?

earnest gazelle
#
 var atlas = new Texture2D(AtlasSize, AtlasSize, DefaultFormat.LDR, TextureCreationFlags.None);
// change and set some pixels.
atlas.SetPixels(index.x, index.y, (int)rect.width, (int)rect.height, pixels);
// save it
File.WriteAllBytes($"{path}.jpg", atlas.EncodeToJPG());
#

My goal is to create some texture atlases and pack them into a texture array.

somber nacelle
#

and is this code where the error is happening?

earnest gazelle
#

Texture array does not support compressed format. Also, it is required read/write textures

#

The error happens when creating texture array.
I know what the problem is

steady moat
earnest gazelle
#

1- set read/write for textures
2- use uncompressed formats

earnest gazelle
somber nacelle
earnest gazelle
#

It does not handle my scenario.

#

I want to have size and start index for each texture in an atlas and pass them into my custom shader.
The custom shader uses a texture array of atlases.

earnest gazelle
somber nacelle
earnest gazelle
#

You said runtime textures is readble/writable. I see it is not.

somber nacelle
#

contrary to what you apparently believe, the code i'm requesting to see is also relevant

#

depends what you are expecting a "root project global variable" to even mean

earnest gazelle
#
 var atlas = new Texture2D(AtlasSize, AtlasSize, DefaultFormat.LDR, TextureCreationFlags.None);
// change and set some pixels.
atlas.SetPixels(index.x, index.y, (int)rect.width, (int)rect.height, pixels);
// save it
File.WriteAllBytes($"{path}.jpg", atlas.EncodeToJPG());

After running it, I see read/write flag is false in the editor for that texture

#

It creates a texture array

   var sample = textures[0];
            var textureArray = new Texture2DArray(sample.width, sample.height, textures.Count, sample.format, false);
            textureArray.filterMode = FilterMode.Trilinear;
            textureArray.wrapMode = TextureWrapMode.Repeat;

            for (var i = 0; i < textures.Count; i++)
            {
                Texture2D tex = textures[i];
                textureArray.SetPixels(tex.GetPixels(0), i, 0);
            }

            textureArray.Apply();

            string uri = path + filename + ".asset";
            AssetDatabase.CreateAsset(textureArray, uri);
            AssetDatabase.Refresh();
#

Error is this line

 AssetDatabase.CreateAsset(textureArray, uri);

Can't create asset.

lean sail
earnest gazelle
#

I mentioned because textures are not readable/writable and uncompressed , so?

lean sail
#

yea u arent gonna be able to take much from roblox, unity is way more complex

somber nacelle
#

once you save it to a file as an asset in your project it isn't exactly a "runtime" texture anymore, is it?

earnest gazelle
#

I got, runtime in unity docs means they are created and used in runtime, so they can set and get.

somber nacelle
#

yes, once you save it as a file and import it into your project it gets that false value because that is the default value for textures imported as assets. in the previous code snippet where you create the texture, it is writable because you have not done anything to it to make it not writable. but that file you created is completely separate, it gets imported into the project with the value set to false. but the texture you have in memory in that code is still writable

heady iris
#

a texture is a texture object, not an image on your disk

earnest gazelle
#

A texture can be a texture asset or a texture object.