#archived-code-general

1 messages Β· Page 129 of 1

gray mural
#

You should consider doing it in Start() I guess ??

somber nacelle
#

or even just in Reset

fervent furnace
#

i believe you will end up with error likes: layer value must be [0,31]...

gray mural
swift falcon
#

Eh not a big deal, just an experiment

gray mural
#

Does somebody know if there is a possibily to do smth like:

private IEnumerator Bla()
{
    // do smth

    if (Bla() Coroutine was stopped)
    {
        print("Stopped");
    }
}
#

so that some action is done, when coroutine is stopped

fervent furnace
#

maybe pass a callback into it

gray mural
fervent furnace
#

and no more yield return after the call back
Bla(Action something)
when finish, calls something() then "yield break"

gray mural
fervent furnace
swift falcon
gray mural
swift falcon
#

You could maybe do something like

if (!coroutine.Running && coroutineWasRunning)```
I assume there's some IsRunning sort of thing, or maybe check if it's null
gray mural
#

oh, not that

gray mural
#

"unreachable code detected"

fervent furnace
#

while(true)

#

dead loop

gray mural
#

any ideas how to stop it? πŸ€”

gray mural
#

it should do some action here:

StopCoroutine(_caretBlinkCoroutine);
_caretBlinkCoroutine = StartCoroutine(CaretBlinkCoroutine());
swift falcon
#

Why can't you just call whatever method after you stop the coroutine?

fervent furnace
#

If you force stop the coroutine i believe you can just call the callback right after it

gray mural
#

I just wondered if there's a better way to do that

fervent furnace
#

And the callback in ienumerator probably wont be called

buoyant crane
#

One will yield until Two() terminates

swift falcon
#

Anyone know what this is stored as for a UnityEvent?

[SerializeField] UnityEvent<object> _event;

_event.Invoke(???);```
gray mural
gray mural
buoyant crane
#

it’s completely optional

lime widget
#

I made a shotgun that shoots at the position of the mouse. I am having a little bit of trouble regarding the spread. This is the code I have. It works good for the most part but with this method the bullet spread depends on how close the cursor is related to my character. How can I make the spread independent of that?


        Vector3 mousePos = Input.mousePosition;
        var aim = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane)) - transform.position;
        for(int i = 0; i < numberOfBullets; i++)
        {
            var dir = (Random.insideUnitSphere * spreadDistance + aim).normalized;
solid mountain
#

rotate towards, but like, for 2d? this is my code

        transform.rotation = Quaternion.RotateTowards(transform.rotation, q, rotateSpeed * Time.deltaTime);```
hollow hound
#

How to debug "The referenced script (Unknown) on this Behaviour is missing!".
Why it doesn't say what object/component is the problem?

gray mural
#

This code throws error, does somebody know if that's possible to do smth like that?

_caretBlinkCoroutine = yield return StartCoroutine(CaretBlinkCoroutineHelper());
solid mountain
#

it does some weird stuff, because it's for 3d and im on 2d

solid mountain
swift falcon
gray mural
solid mountain
#

yield return;(<-this thing)

lime widget
somber nacelle
gray mural
somber nacelle
#

they are literally calling yield return StartCoroutine();

solid mountain
solid mountain
#

i didn;t know, the most common issue is semicolon

gray mural
#
// works
_caretBlinkCoroutine = StartCoroutine(CaretBlinkCoroutineHelper());

// works
yield return StartCoroutine(CaretBlinkCoroutineHelper());
somber nacelle
solid mountain
#

it's not smol

lime widget
solid mountain
#

still anyone know something like RotateTowards but for 2d?

hollow hound
wind palm
lime widget
hollow hound
wind palm
#

You need to read the error

wind palm
solid mountain
wind palm
#

Just under the log in a separate section

solid mountain
#

(this isn't c#?)

wind palm
solid mountain
lime widget
#

Good luck with that xd

solid mountain
solid mountain
#

welp, time to show off that I am a good dev

#

and also die

hollow hound
lime widget
wind palm
solid mountain
#

oh my god I hate quaternions

wind palm
#

If I was at home I would give you my script for a turret

solid mountain
wind palm
solid mountain
#

i think

buoyant crane
wind palm
solid mountain
leaden ice
solid mountain
swift falcon
#

Anyone know if there's a way I can make Parameter serialized in the inspector?

[Serializable]
public class EventPlus<T>
{
    public UnityEvent<T> Event;
    public T Parameter;
}

[SerializeField] EventPlus<object>[] _eventPlusArr;```

Or if there's any way to invoke a UnityEvent<object> with the parameter from the inspector like in the image below:
```cs
[SerializeField] UnityEvent<object> _event;

_event.Invoke(???);```
leaden ice
# solid mountain hm

E.g.

transform.right = Vector3.RotateTowards(transform.right, targetDirection, speed * Time.deltaTime, 0);```
solid mountain
leaden ice
#

Hey you asked

swift falcon
leaden ice
#

Idk what Event is in this context

swift falcon
#

That's what you wrote

quartz anchor
#

How does physics.sphereCast get it's normal for objects that it hits? Does it return the normal of the face of the collider thats closest to the sphere's origin?

swift falcon
#

I'm looking for a way to use the parameter you can write into a UnityEvent from the inspector

#

Like the 5 from the image above

leaden ice
swift falcon
solid mountain
#

i have to study quaternions, whenever it comes on rotating i screw up

swift falcon
#

Seems like this is the only thing I can do but it's very ridiculous

[Serializable]
public class EventPlus<T>
{
    public UnityEvent<T> Event;
    public T Parameter;
}

    [SerializeField] EventPlus<float>[] _eventPlusFloat;
    [SerializeField] EventPlus<string>[] _eventPlusString;
    [SerializeField] EventPlus<bool>[] _eventPlusBool;
etc

            foreach (var eP in _eventPlusFloat)
            {
                eP.Event.Invoke(eP.Parameter);
            }
            foreach (var eP in _eventPlusString)
            {
                eP.Event.Invoke(eP.Parameter);
            }
            foreach (var eP in _eventPlusBool)
            {
                eP.Event.Invoke(eP.Parameter);
            }
etc```
leaden ice
swift falcon
#

A workaround because Unity won't let me use the parameter in the UnityEvent
I just want to do something like:

[SerializeField] UnityEvent<object> _event

_event.Invoke(_event.parameter);```
But there is no _event.parameter
kind atlas
#

hi I'm programming a health bar system that has a health bar with a shield bar over the health, similar to what you'd find in a fighting game. it mostly works but I'm having an error where the visual for the shield bar doesn't zero out before the health bar starts taking damage. the data is correct but the fill for the visual stops at 0.18181 leaving a part of the shield bar. both the shield and the health have identical code and the fill for the health bar goes to 0. I'm not sure how to fix this. the code is written across 4 scripts. This is where i got the original code from https://youtu.be/cR8jP8OGbhM?t=1077

Stat Manager - https://hatebin.com/tcjgbfklyz, Damage Manager - https://hatebin.com/dneuehugdd, Shield Point Manager - https://hatebin.com/yhsqnkfotd, Shield Bar Visual- https://hatebin.com/vgblqcsqcn

🌍 Get my Complete Courses! βœ… https://unitycodemonkey.com/courses
πŸ‘ Learn to make awesome games step-by-step from start to finish.
Let's make 3 different Effects for showing Damage Taken in a Health Bar!
βœ… Get the Project files and Utilities at https://unitycodemonkey.com/video.php?v=cR8jP8OGbhM

Sekiro's Vitality Posture System built in Unity
ht...

β–Ά Play video
swift falcon
lime widget
#

Bullet Shotgun spread

surreal adder
#

Why is my prefab icon so small?

#

Asked that before but i still didnt solve it

trim schooner
#

A server full of Unity devs, in the Unity discord is pretty much going to say: yes

Also, not a code question, that shouldn't be in here.

versed loom
#

Hello! Why I cant access any namespace if I already have the package installed?

heady iris
versed loom
maiden sedge
#

Hi is it possible to make an ingame microtransaction system with steamworks ?

#

cause for my game that uses steamworks a lot (online multiplayer fps) I think microtransactions are better than DLCs

spare dove
#

Best practice question; I have several different types of items inheriting from a base class, whats the smoothest way to check which type an item is?

potent sleet
#

if you have a lot of diff types instead of if statements or giant ass switch maybe is best doing lookup table with dictionary ?

spare dove
cursive gorge
#

If I turn on gpu instancing from the material and turn on static batching from the editor, will they conflict?

#

or improve performance 2x

abstract fern
vague jolt
#

How do i finish decalring this:

    public class References
    {
        public List<GameObject> structures = new List<GameObject>();
        public List<GameObject> cables = new List<GameObject>();
        public List<int> connectedTo = new List<int>();
    }

    new Dictionary<string, References> references = new Dictionary<string, References>()
    {
        {"Red1",}
    };

To have the same workings of this mess

    //input red 
    public List<GameObject> connectionsRed1 = new List<GameObject>();
    public List<GameObject> cablesRed1 = new List<GameObject>();
    public List<int> connectionPointRed1 = new List<int>();

    //input green
    public List<GameObject> connectionsGreen1 = new List<GameObject>();
    public List<GameObject> cablesGreen1 = new List<GameObject>();
    public List<int> connectionPointGreen1 = new List<int>();


    //output red
    public List<GameObject> connectionsRed2 = new List<GameObject>();
    public List<GameObject> cablesRed2 = new List<GameObject>();
    public List<int> connectionPointRed2 = new List<int>();

    //output gren
    public List<GameObject> connectionsGreen2 = new List<GameObject>();
    public List<GameObject> cablesGreen2 = new List<GameObject>();
    public List<int> connectionPointGreen2 = new List<int>();
#

i just don0t know how to declare the value part of the dictionary

vague jolt
steady moat
#

You should review the name of your class. References is pretty bad name for what you are doing there.

vague jolt
#

is the list of all the references that my gameobject is storing to other gameobjects

#

what this rappresent is the connections in a network

steady moat
#

Also you might want to do this:

var dict = new Dictionary<string, References>()
        {
            {"Red1", new References()}
        };
steady moat
#

It is like calling a class class.

vague jolt
#

is tecnically a structure that is then joined to other structure using cables

#

here is store the connections

steady moat
#

It must have a purpose ?

steady moat
#

I mean, it compile.

vague jolt
steady moat
#

What are you doing ?

vague jolt
steady moat
somber wyvern
#

Hello, does Unity have a specific owner client ID value to represent a null ID? I couldnt find one in the docs.

public NetworkVariable<ulong> CurrentInteractorClientID = new NetworkVariable<ulong>();

I have something like this to keep track of the client that is holding an object, but when its not holding anything, I am not sure what to set this value to. I couldnt find anything in the docs, so I am curious if you all have an answer

Im considering just using the max value for ulong but I dont know if unity has a specific recommendation

vague jolt
#

each structure has two type ofg connections, red and green , the can be both inpuit or output

#

1 and 2 rappresent that, i know those are not clear but i can't really change it

steady moat
#

What if you decide to change the color ?

vague jolt
#

i can't

steady moat
#

Are you serious O.o

vague jolt
#

i am making a simulation of something that already exist

#

if i changed it it would be wrongh

#

same reason i use 1 and 2 is because the original game uses 1 and 2

steady moat
#

What if you decide to change the theme of your application

#

So, green is input ?

vague jolt
vague jolt
#

wait

steady moat
#

Is it red then ?

vague jolt
#

i send you an immage

vague jolt
steady moat
#

What is the function of the devices ?

vague jolt
steady moat
#

Alright, so what the red cable does ?

vague jolt
#

you can use the inputs in the green and red cable and output it to the red and green cable

vague jolt
#

the reason there are two cables is so you can use the same id without the data adding togheter

steady moat
#

So, can we call it something like Link ?

vague jolt
steady moat
#

So, a machine has link. This particular machine has two link. You do not need to identify those link inside the class don't you ?

#

You could have a list of link.

#

List<Link> instead of a dictionnary.

#

As you might have other type of machine in the future

#

One with more than 2 links

vague jolt
#

they can have only 1 or two links

steady moat
#

Alright, I'm done. You understand nothing of what Software Architecture is.

vague jolt
#

thanks any way

steady moat
vague jolt
vague jolt
dawn nebula
#

Does Unity have some built in Timer class with callbacks I can hook into?

somber nacelle
#

and what kind of callbacks you are expecting

#

if this is for some sort of gameplay timer then no, although there is a timeSinceLevelLoad property on unity's Time class. you'd have to write your own using a deltaTime timer in Update or c#'s StopWatch class or something

steady moat
# vague jolt like i am onestly curious, i not a good programmer at all, so if i can understan...

Software Architecture is all about minimizing change to increase the maintainability of a software. With the approach you are taking, you gonna have a hard time implementing the other functionality; Those that are in the game your copying.

To create a solid architecture, you must consider the concept you are representing. You must define what we call Domain-Specific Language (https://en.wikipedia.org/wiki/Domain-specific_language). In your case, that would Machines, Links, Input, Output, etc. If you do not define those concept, you never going to be able to have a stable structure as it will not represent correctly your application. Each Business Rule you gonna implement will always require a reorganization of your structure. You are already suffering from this and you are probably not far in your implementation.

vague jolt
#

wizzards know everything

steady moat
#

Bro went to school and listened.

#

Those paper are not only for show.

vague jolt
steady moat
#

This going to follow everywhere till you have the motivation to make clean code.

vague jolt
steady moat
vague jolt
#

i like learning by being forced to find solution other than studying the theory, at least for coding

steady moat
#

Alright, just stayy curious. Because the way you were earlier is the worst way to approach any issue you will have.

vague jolt
#

πŸ’€

steady moat
#

πŸ’€

dawn nebula
vague jolt
dense tusk
#

'ello lads. i ripped off some code and did some experimenting with it, and i am confused by how a certain part of it works. it does work, but i don't understand how: https://paste.ofcode.org/AqUUYq7BnaqE7UvEDJ5YJw

in particular, it's the

//Sets a target position (tbh don't know how this works, but it does)
Vector3 targetPosition = holdPosPoint - selectedRigidbody.transform.position;
``` that i don't get. can anyone tell me what this is doing exactly?
honest edge
#

hey guys. Anyone know what's going on with "UnityException: Load is not allowed to be called during serialization, call it from Awake or Start instead." Got this since the new LTS. I just upgraded and this is annoying, even if it works in reality.

dense tusk
#

think that means something is being incorrectly assigned outside of start or awake

dense tusk
#

i guess that's the wrong part to focus on. i'm confused as to this is getting the correct location for an object to move.

honest edge
#

check this. there's an example for exactly that. pretty simple.

dense tusk
#

like, i get that it's subtracting the vectors, but i don't understand how that's getting me the correct position for what i'm doing.

honest edge
#

you substract both of these vector. this gets you the vectorial "distance"

#

You then change the velocity by using this distance and slowing going in that direction using time.deltatime

buoyant crane
honest edge
#

"targetPosition * forceAmount" is the same as the substraction but you multiply each of them by this number

buoyant crane
honest edge
buoyant crane
#

weird that it only created the error after you updated UnityChanThink

west lotus
honest edge
honest edge
#

most thing that requires timer, I just use a coroutine personnaly

west lotus
#

Well okey, but if you need to time lots of stuff you might as well create some sort of utility class

honest edge
#

this does look like a nice library though. avoid a few headaches for creating variables mostly. What do you need something like that for?

west lotus
#

And if you do that you might as well use a pre built and tested solution

dawn nebula
honest edge
#

My though as well. I like it even though I don't need it

#

your point is that it's not maintained anymore?

west lotus
#

My point?

#

Dude wanted a timer with a callback

#

i gave him a timer with a callback

#

There is no point here to be had

honest edge
#

oooh. I though you were asking the question lol. my bad

west lotus
#

We use this lib in our games and are very happy with it so I share it with people who need to time stuff

honest edge
#

this conversation suddenly make sense in my head πŸ˜‚

#

thanks for sharing

dawn nebula
#

It doesn't seem like the TimerManager has DontDestroyOnLoad

honest edge
#

store the result between scene or something?

#

or just dont destroy one class in which you have it initialized

west lotus
candid moon
#

https://medal.tv/games/requested/clips/1eNHMUeJEcuQI4/d1337XRkawIY?invite=cr-MSxKTnYsMjYzNjQxOTcs

Hello,
I am attempting to make a restaurant game and the npcs coming in are supposed to sit down (animation) after their transform being set to a gameobject's transform
For some reason there is always an offset on the y - Axis, I am not sure why
I am also unable to move the object's Y axis in runtime

Components:

Rigidbody
2x Colliders (one with, one without trigger)
Navmesh Agent
Script

Animator in the child object

private void OnTriggerEnter(Collider other)
    {
        if (other.name == "WalkToPos")
        {

            nav.ResetPath();

            animator.SetBool("isWalking", false);

            nav.updateRotation = false;
            Rigidbody rigidbody = GetComponent<Rigidbody>();

            rigidbody.velocity = Vector3.zero;
            rigidbody.constraints = RigidbodyConstraints.FreezeAll;

            StartCoroutine(CustomerSit(other.transform.parent.Find("SitPos").gameObject));

        }
    }

IEnumerator CustomerSit(GameObject sitPos)
    {
        yield return new WaitForSeconds(0.4f);

        transform.position = sitPos.transform.position;

        print(transform.position + " " + sitPos.transform.position);
        print(transform.position);


        transform.localRotation = Quaternion.Euler(0, 0, 0);
        transform.rotation = Quaternion.Euler(0, 0, 0);

        Animation customerSitAnim = GetComponentInChildren<Animation>();

        animator.SetBool("isOrdering", true);

        ChooseRandomItem();

        sitting = true;
    }```

Watch Bug Help 18/6/23 and millions of other Requested videos on Medal, the largest Game Clip Platform.

β–Ά Play video
vale wren
#

what's the best way to make an infinite looping scroll? I know there's assets but im trying to figure out how to do it myself. I initially tried doing an invisible "teleport" once I go past a boundary, but if I drag past, say, 0.8 and try to teleport to 0.2, dragging further will continue to take me past 0.8. then it just flickers because it tries to teleport again.

now I'm thinking of doing a dequeue system, but I still run into the same issue.

gray mural
#

I need to yield return Coroutine (as you have said before) to wait until coroutine is finihsed and this coroutine should be _caretBlinkCoroutine

#

So it's possible to do _caretBlinkCoroutine = StartCoroutine(CaretBlinkCoroutineHelper());

#

and possible to do yield return StartCoroutine(CaretBlinkCoroutineHelper());

#

but this is impossible

#

and that's what I am trying to achieve:

private IEnumerator CaretBlinkCoroutine()
{
    _caretBlinkCoroutine = yield return StartCoroutine(CaretBlinkCoroutineHelper());

    IEnumerator CaretBlinkCoroutineHelper()
    {
        WaitForSeconds _caretBlinkRateWait = new WaitForSeconds(caretBlinkRate);

        while (true)
        {
            yield return _caretBlinkRateWait;

            ChangeAlpha(0f);

            yield return _caretBlinkRateWait;

            ChangeAlpha(1f);
        }
    }

    ChangeAlpha(1f);

    void ChangeAlpha(float alpha)
    {
        Color newColor = _caretImage.color;
        newColor.a = alpha;
        _caretImage.color = newColor;
    }
}
honest edge
#

you don't need the startCoroutine in an IEnumerator

gray mural
vale wren
#

i have a bunch of buttons in a scrollrect, is there some way to reorder them during runtime

soft shard
honest edge
#

@gray mural What are you trying to achieve exactly? I might be missing the context of what you're trying to do here.

gray mural
#

for example when I do:

StopCoroutine(myCoroutine);

it does something at the end (e.g. "bye bye" in console)

honest edge
#

do you mean StopCoroutine?

gray mural
honest edge
#

In general, this is considered bad pratice to use stopCoroutine. Just because there's proabably a better way. You can't really know where the coroutine will actually stop. If you need a very specific behavior to happen, you won't have control over when it does stop.

#

controlling the when using variable or something else could be an option.

#

From what I get, you want to get your caret to flash once and then do something, right?

#

Why not in this case have a variable global to your class, call it "endCaret" or something. And in your coroutine, you have yield waiting for this to happen, and then trigger whatever you need.

#

yield return new WaitUntil(endCaret);

soft shard
#

If the endCaret variable is a Coroutine type, you should also be able to call something like yield return StartCoroutine(endCaret); or endCaret = StartCoroutine(...); yield return endCaret;

gray mural
#

caret is constantly blinking

#

and when coroutine stops - caret should imediately become visible (alpha 1f)

gray mural
#

and it won't call endCaret = StartCoroutine(...); until endCaret Coroutine is not finished

gray mural
soft shard
# gray mural and it won't call `endCaret = StartCoroutine(...);` until `endCaret` Coroutine i...

Really? Interesting, I was using something similar earlier today for a rebind system and some logging and seemed to only happen once, though I often have a function to manage coroutines with variables, something like:

Coroutine co;

void DoThing(IEnumerator next)
{
if(co != null) {StopCoroutine(co);}
co = StartCoroutine(next);
}

That wouldnt be the same as yielding it inside a coroutine though, just would prevent multiple coroutines from starting if the previous one wasnt finished (or reset to null) already

honest edge
honest edge
#

I feel like the solution to your issue isn't really a coroutine but simply an event.

If you have a class to manage that inputField, you should have a property for the content of it.

If you have something like this:

ashen yoke
#

just figured i could unload all the projects i dont need in the solution and hide them

#

instant vs speedup

honest edge
#
public event Action<string> OnInputChanged = null;
private string _input = "";
public string Input {
    get => _input;
    set {
        if (_input != value) {
            _input = value;
            OnInputChanged?.Invoke(_input);
        }
    }
}

Then, you call it where you need it:

Input.onInputChanged += Somefunction;
private void Somefunction(string value) {
    if (value==="smth") {
        StopCoroutine("caretAnimation");
    }
}
#

@gray mural Or that could be a simple function inside the set instead of an event if that's suposed to apply to any input whatsoever. litle less flexibility.

That coroutine could be on the class of the inputfield itself, and you could call it to start and stop the caret animation using the same technique.

honest edge
#

lol. typescript sickness

#

My day job is mostly typescript so I typed too fast haha

latent latch
#

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

latent latch
placid island
#

oh sorry

gray mural
gray mural
#

like this:

private void KeyDownEvent(Event evt)
{
    switch (evt.keyCode)
    {
        case KeyCode.Backspace:
            BackspaceKey();
            return;

        case KeyCode.Delete:
            return;
    }

    ValidateInput(evt.character);
}

private void ValidateInput(char c)
{
    if (c == '\0' || c == '\t' || c == '\n')
        return;

    text += c;

    AlignCaret();
}
gray mural
#

@honest edge @soft shard thank you both for your help, that's the solution I have done after all:

private void CaretBlink()
{
    if (_caretBlinkCoroutine != null)
        StopCoroutine(_caretBlinkCoroutine);

    ChangeAlpha(1f);

    _caretBlinkCoroutine = StartCoroutine(CaretBlinkCoroutine());

    IEnumerator CaretBlinkCoroutine()
    {
        WaitForSeconds _caretBlinkRateWFS = new WaitForSeconds(caretBlinkRate);

        while (true)
        {
            yield return _caretBlinkRateWFS;

            ChangeAlpha(0f);

            yield return _caretBlinkRateWFS;

            ChangeAlpha(1f);
        }
    }

    void ChangeAlpha(float alpha)
    {
        Color newColor = _caretImage.color;
        newColor.a = alpha;
        _caretImage.color = newColor;
    }
}
honest edge
#

If you already have something to handle it, yes it is. It was just the idea

royal pulsar
#

I have this process that I want to handle

#

right now I do it via 2 scripts like this:

public class Interaction : MonoBehaviour
{
    public UnityAction onInteractEvent;
    private Transform aim;
    [SerializeField] private float range;

    private void Awake()
    {
        aim = GetComponentInChildren<Transform>();
    }
    public void Interact()
    {
        // Shoot raycast and return hit object (or null)
        RaycastHit2D hit = Physics2D.Raycast(aim.position, aim.right, range);
        if (hit)
        {
            GameObject hitObject = hit.transform.gameObject;
            TryInteractWithObject(hitObject);
        }
        onInteractEvent?.Invoke();
    }

    private void TryInteractWithObject(GameObject objectToInteractWith)
    {
        if (objectToInteractWith.TryGetComponent(out Interactable interactableObject))
        {
            interactableObject.TriggerInteraction();
        }
    }
}
#

Both scripts are the same except one does TryInteract and one does TryHit

#

how can I avoid this code duplication?

regal epoch
#

is there any way the basic unity ads can mess up a game? I had a working mobile game, and wanted to add the ads. but now its completely broken. the starting screen doesn't show text anymore and when i click the (only) button to start the game it gets stuck on an infinite loop clicking itself and doesn't start the game. tried looking into the logs with logcat but couldn't find anything

#

well i found the problem. it was the ads initializer i added on the starting screen. when i removed it, the game works fine. anyone would happen to know why?

latent latch
royal pulsar
#

I'm thinking of just splitting the big script into a Fire() script, a Raycast() script, and then I can apply either a Interact() or Hit() script

#

i feel like interfaces could be useful but im not 100% sure when to use them,

#

I can communicate the scripts via unity events

latent latch
#

Usually when I think of interact scripts, they are usually done without needing to know the exact derived type that's hit, and as such you just use the override methods of your implementations

royal pulsar
#

I see

#

To be honest my current scripts are purely compositional

latent latch
#

Interact keyword meaning that there's some sort of functionality that you can do with the object, either attack, talk, trade

royal pulsar
#

so my enemy is just a health component, collisionattack component, AImovement component. There is no concrete "enemy" class or anything

latent latch
#

Yeah, via virtual function implementations

royal pulsar
#

ah i see, my project is just structured too differently

latent latch
#

not entirely sure of a composition or an ecs type of way

#

if anything, a switch of checks might be what you need

#

but this still comes to my previous question about having multiple interface types

#

though if you've got differeny raycast methods depending on input then that's not a problem

celest moss
#

Hey im trying to setup a position constraint for the purple aura in my game. But adding a new constraint source doesnt apply any constraint to the gameobject. I am confused on how to use the position constraint and untiy script documentation doesnt help me either

latent latch
#

I think there may be values you need to toggle with the constraints when you create one

#

I forget

#

It's like weight or something

celest moss
rocky jackal
#

how can i check if a bounding box of one object is inside the bounding box of another object ? im currently cecking it like this but it wont stop scaling down the object

regal epoch
#

it looks like your scaling it down when its not colliding

#

but i could be wrong

rocky jackal
#

im scaling it down when the second bounding box isnt inside the first one and it should theoretically stop once the second object has been scaled down enough to fit into the first object

#

its for an inventory system

regal epoch
#

maybe put extra true statements in? right now you're checking if the first one is false or the second one is false. but not one false and the other true. so when they're both false it still runs the code

rough crown
#

vscode question. How do i move the "2 references" to the right?

regal epoch
rough crown
#

oh so it's called a codelens

#

yikes so apparently they don't have the feature to move it to right like in intellij (illustrated below)

ashen yoke
ashen yoke
rough crown
#

yeah couldn't look cleaner

ashen yoke
#

you should bind a hotkey to find references

normal dust
#

can anyone familiar with zenject help me make a dontdestroyonload singleton equivalent? i just picked up zenject and im confused to say the least ._.

lethal tusk
#

Is there a way to load all scenes once you open the game? There are some scene in my game with some script that I need to load as soon as the game launched. The reason is These scripts generate some data that I need on the first scene.

normal dust
ashen yoke
normal dust
#

you could put everything you need in the first scene and then load additive

lethal tusk
ashen yoke
#

it has params that allow you to run code before scene loads

lethal tusk
#

I have an array of bools in one script, like this: public bool[] cubeList = {true, false, false, false};
and I save this to a json file, If i launch the game for the first time It makes a an array of bools without any value.

#

So the game wount work cuz I need those values

ashen yoke
#

create an empty scene, set it as the first, do whatever loading you need, then load from that scene the actual game scene

#

its a very common pattern

lethal tusk
#

sure thanks

ashen yoke
#

or use RuntimeInitializeOnLoad

lethal tusk
#

just one more question, I should use singeltons to share the data right?

normal dust
#

you could

ashen yoke
#

singletons are the most basic global access pattern, its always present in any game, in various amounts

#

should you? depends on your project and your skill level

#

there are alternatives that grow in complexity in an attempt to remedy the shortcomings of it

normal dust
#

mr cache do you know anything about zenject?

ashen yoke
#

yes

#

and container in DI has the same properties of a singleton

#

just hidden further

normal dust
#

so if i bind something to it, it should remain in the next scenes?

ashen yoke
#

refer to docs

#

πŸ™‚

#

which do you use?

#

extenject?

normal dust
#

yes

#

is there a difference?

ashen yoke
#

did you read this?

normal dust
#

i didnt but i read about project context so i thought the way to do that would be with it

#

i dont understand whats the use of the project context then

ashen yoke
#

im reading and i dont understand your issue

#

project context is already DDOL?

normal dust
#

I added it to my first scene and it doesnt seem to make another instance on the next scene

#

my problem is im trying to get my data from firebase and bind IDatabase to that instance and only then to load the next scene

ashen yoke
#

it says any scene that contains scene context will first load project context

#

after that it will singleton DDOL for the lifetime

normal dust
#

yea ik its project>scene>gameobject

#

idk why but these docs are very confusing to me

#

should i add the project context to my first scene?

ashen yoke
#

i dont know how extenject handles it, i dont think it needs to be present in any scene

normal dust
#

i dont think i should cause its a prefab

ashen yoke
#

it should be a prefab that is automatically instantiated

normal dust
#

yea so then how would i inject FromInstance

#

ive been stuck on it for hours chatgpt doesnt help unfortunately

ashen yoke
#

so your issue is that binds on project arent injected in scene?

normal dust
#

sound about right i think

#

from what i understand project context binds whatever i need once and thats it for the rest of the game runtime

ashen yoke
#

yep seems that way

#

are your scenes properly setup?

#

scene context present?

normal dust
#

thats probably where im not doing things right

#

in the first scene do i need a scene context?

normal dust
#

i tried doing that with the database instance being ddol and loading scene additive both dont work

ashen yoke
#

validation passes?

normal dust
#

yep

ashen yoke
#

what happens?

#

nothing passed? null passed? db itself loads?

normal dust
#
public abstract class DatabaseDependant : MonoBehaviour
{   
    protected IDatabase _database;
    [Inject]
    protected virtual void Construct(IDatabase database)
    {
        _database = database;
    }
    protected abstract void LoadData();
public class CurrencyManager : DatabaseDependant
{
    protected override void LoadData()
    {
        print(_database == null);
        print(_database is null);
        Pawins = (float)_database.GetValueFromDatabase("Pawins");
        Pawllars = (uint)_database.GetValueFromDatabase("Pawllars");
    }

basically prints "True" at these debugs
NullReferenceException: Object reference not set to an instance of an object

ashen yoke
#

which line

#

alright, what calls LoadData()

normal dust
#

its called from start

ashen yoke
#

can you put a breakpoint in Construct and LoadData

#

see in which order they are called

#

and observe _database value

normal dust
#

i can but ill mention i even tried making start ienumerator and wait 5 seconds

#

and it still said its null

ashen yoke
#

then just in Construct

normal dust
#

mmkay

#

its totally different from breakpoints in normal programming one sec ill google how to do it in unity

ashen yoke
#

its the same, highlight the line in visual studio, press F9, press F5 to connect to unity, play in unity

normal dust
#

then nothing is happening

#

like it doesnt reach the breakpoint

ashen yoke
#

you arent hitting it?

normal dust
#

nope

ashen yoke
#

then you have something broken in zenject scene/whatever that mono is on setup

#

zenject ignores it

normal dust
#

do i need a scene context on that scene?

ashen yoke
#

possibly, it may be needed by zenject to indicate that scene scene is zenject enabled, maybe to perform scene initialization

#

most likely what it does is it loads first since its high in SEO, disables all scene objects before they have a chance to receive Awake, initializes/injects them, then enables

normal dust
#

so i have a projectcontext in my first instance with an installer on it binding from instance, and an empty scene context in the next scene and it says
ZenjectException: Assert hit! Tried to create multiple instances of ProjectContext!

#

maybe my whole approach is wrong how would i go about doing what i need

#

load the snapshot from firebase, bind that instance, load next scene and have it injected where needed

harsh ridge
#

anyone know how to detect when a vr player pulls a controller towards themself?

steep herald
#

not a VR dev, but I assume you can simply use the controllers XZ distance from the headset's XZ coords, ignoring the Y? If the distance delta over a certain amount of time is greater than your threshold, then make shiny things happen

#

Or, to ignore the potential bias caused by dragging the controllers ahead of you but towards the center of your body, you could figure out the forward vector that represents the facing direction of the player, negate that vector, and see how far the controllers have traveled along that vector

#

which I'm guessing the only harder part about this is determining the player's forward vector if it's not persistent in your game, and if there aren't libraries that already do this. Likely inferred from the controllers orientation and the headset's over a set amount of time

grizzled tapir
#

Im using the textmesh pro TMP_Dropdown UI element and im adding items to the dropdown menu through code. I then want to add a method in their OnClick() event, how could I do this through code?

wide dock
#

Yo, I have a question...
How do I save a 2D/3D array which is being generated by my AssetPostProcessor on a ScriptableObject so that's it available during game runtime?

[field:SerializeField]
public float[][][] array3D { get; private set; }

My method for generating the array is being called, but it's null at runtime

somber nacelle
#

unity does not support serializing multidimensional or jagged arrays so you'd have to store that data some other way

wide dock
#

Oh, I see..

wide dock
wind palm
#

Then it'll save as a single array

wide dock
#
[Serializable]
public class MyArray<T>
{
    private T[] elements;
        
    public T this[int index]
    {
        get => elements[index];
        set => elements[index] = value;
    }
        
    public MyArray(int size)
    {
        elements = new T[size];
    }
}
[field:SerializeField]
public MyArray<MyArray<MyArray<float>>> generatedPattern { get; private set; }

public void GenerateAttack()
{
  generatedPattern = new MyArray<MyArray<MyArray<float>>>(repeatCount);
  for (int r = 0; r < repeatCount; ++r)
  {
    generatedPattern[r] = new MyArray<MyArray<float>>(inBatchBulletCount);
      for (int i = 0; i < inBatchBulletCount; ++i)
      {
        generatedPattern[r][i] = new MyArray<float>(batchCount);
      }
  }
  ...
wide dock
#

Thanks

fervent furnace
#

for accessing a[i][j][k] it should be i*sizeof(j)*sizeof(k)+j*sizeof(k)+k, the order of your indexer looks a bit different though it works but i j k have to be inversed

wind palm
twilit wren
#

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

vocal root
#

Any easy way to generate a visual grid like this?

#

I tried with line renderer and gyzmos but all I get is a square in the middle of the map

fervent furnace
#

i use handle and gizmos to show visual grid and debug infos...

vocal root
# potent sleet show what you tried

First I tried to generate cubes arround but every single one spawns on the same spot

private void GenerateCubes()
    {
        // Obtener la posiciΓ³n del GameObject
        Vector3 position = objetoActivo.transform.position;

        // Generar los cubos en las posiciones alrededor del GameObject
        for (int x = -1; x <= 1; x++)
        {
            for (int y = -1; y <= 1; y++)
            {
                for (int z = -1; z <= 1; z++)
                {
                    // Excluir la posiciΓ³n central
                    if (x == 0 && y == 0 && z == 0)
                        continue;

                    // Calcular la posiciΓ³n del cubo alrededor del GameObject
                    Vector3 cubePosition = position + new Vector3(x, y, z);

                    // Instanciar el cubo en la posiciΓ³n calculada
                    Instantiate(cubePrefab, cubePosition, Quaternion.identity);
                }
            }
        }
    }
#

Then with LineRenderer but only a square in the middle if lucky

private void GenerateGrid()
    {
        // Obtener la posiciΓ³n central del GameObject
        Vector3 center = transform.position;

        // Calcular el tamaΓ±o del cuadrado
        float halfGridSize = gridSize * 0.5f;

        // Calcular las posiciones de los vΓ©rtices del cuadrado
        Vector3[] squareVertices = new Vector3[]
        {
            new Vector3(center.x - halfGridSize, center.y, center.z - halfGridSize),
            new Vector3(center.x - halfGridSize, center.y, center.z + halfGridSize),
            new Vector3(center.x + halfGridSize, center.y, center.z + halfGridSize),
            new Vector3(center.x + halfGridSize, center.y, center.z - halfGridSize),
            new Vector3(center.x - halfGridSize, center.y, center.z - halfGridSize) // Repetir el primer vΓ©rtice para cerrar el cuadrado
        };

        // Configurar el LineRenderer con las posiciones de los vΓ©rtices
        lineRenderer.positionCount = squareVertices.Length;
        lineRenderer.SetPositions(squareVertices);
    }
#

Its my first time using this stuff anyway

vernal compass
#

Hey, it's my first time using BoxCast and I'm trying to make a simple ground detection for my character, for some reason the BoxCast it is only returning true for 1 frame when the character hits the ground instead of always being true

I'm not sure if it this is how it works or if I'm doing something wrong

    {
        Gravity();
        isGrounded = GroundCheck();
        rigidBody.velocity = new Vector3 (transform.forward.x * horizontalMovementInput * standWalkSpeed,
                                          rigidBody.velocity.y,
                                          transform.forward.z * horizontalMovementInput * standWalkSpeed);
    }

    void Gravity()
    {
        rigidBody.velocity = new Vector3 (rigidBody.velocity.x, -gravityValue, rigidBody.velocity.z);
    }

    bool GroundCheck()
    {
        if(Physics.BoxCast(transform.position, groundCheckBoxSize, -transform.up,
                            transform.rotation, groundCheckMaxDistance, groundCheckLayerMask))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawCube(transform.position - transform.up * groundCheckMaxDistance, groundCheckBoxSize*2);
    }```
heady iris
#

sphere/box/capsule casts ignore any colliders they start in

vernal compass
#

I see so if I cast it inside the ground collider it won't return true
Any way to work around that?

heady iris
#

You can combo it with an overlap box query.

#

I do that in one of my games. The big monster enemy needs to know when the ceiling is too low to stand upright

#

so I do a combination sphere cast and overlap to get the amount of headroom

vernal compass
#

Never heard of overlap box query, how exactly does it work?

heady iris
#

You ask for every collider that overlaps with a box.

#

you can also just ask if anything overlaps a box at all

#

So you can share some of the parameters with the box cast

#

A box overlap might actually make more sense here

#

(so, you would discard the boxcast)

vernal compass
#

I see, I'll try it! Thank you!

heady iris
#

<@&502884371011731486> the spam was posted in many channels

potent sleet
#

yup

oblique spoke
heady iris
#

Ah, gotcha. I did notice it's been chugging today.

verbal shadow
#

Hello, i have problem with netcode for gameobject. When i try to move a cube like in this code for exmeple on Host the cube scale stay on basic scale but on client the cube turn on scale *2. on my cube there is network object and network transform so i dont understand.

using Microsoft.Cci;
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;

public class Reveal : NetworkBehaviour
{

    public Transform boule;
    public bool hasMoved;
    private Vector3 startPosition;
    private Vector3 endPosition;
    private float speed = 3f;
    private float journeyLength;

    void Start()
    {

        hasMoved = true;
        startPosition = transform.position;
        endPosition = startPosition + new Vector3(0f, 0f, 0.4f);
        //journeyLength = Vector3.Distance(startPosition, endPosition);
    }

    void Update()
    {
        float distCube = Vector3.Distance(transform.position, boule.position);

        if (Input.GetKeyDown(KeyCode.E))
        {
            StartCoroutine(MoveCube());
            BouleRougeServerRpc();
        }
    }

    [ServerRpc(RequireOwnership = false)]
    void BouleRougeServerRpc()
    {
        BouleRougeConfirmClientRpc();
    }

    [ClientRpc]
    void BouleRougeConfirmClientRpc()
    {
        StartCoroutine(MoveCube());
    }


    IEnumerator MoveCube()
    {
        hasMoved = false;

        float elapsedTime = 0f;

        while (elapsedTime < speed)
        {
            float fracJourney = elapsedTime / speed;
            transform.position = Vector3.Lerp(startPosition, endPosition, fracJourney);
            elapsedTime += Time.deltaTime;
            yield return null;
        }

        transform.position = endPosition;
    }
}```
glossy basin
#

Hello there, I have been reading a bit about abstraction, and right now I canΒ΄t figure out which scenarios are suitable for each type of asbtraction, so lets say, when should I use interfaces over inheritance and when should I use abstract classes over the 2 abstraction methods I mentioned? Any help is appreciated!
What are the specific use cases for them?

honest edge
#

Do you mean factory pattern?

#

and for unity specifics, I like Jason's videos

glossy basin
honest edge
#

these two sources will get you probably 80-90% of the way

glossy basin
glossy basin
honest edge
#

This is great to start thinking in pattern right at the start of a project to avoid being stuck to old code that doesn't fit and refactor a lot

glossy basin
#

As some scripts I have are pretty much clones

#

So I have a player health script and then an AI health script which is the exact same thing but with extra stuff

honest edge
#

not all patterns are applicable to unity or gaming in general, but here's another source for more gaming focused pattern design

glossy basin
honest edge
#

if you get through all videos from Jason, you'll find the right fit I'm sure. Factory and Command patterns are the most common imo

#

more game design focused

glossy basin
honest edge
# glossy basin Very useful info, thank you very much!

to your specific case, maybe start here: https://www.youtube.com/watch?v=ll6bxQGkyCk

Check out the Course: https://bit.ly/3i7lLtH


Learn how to use the Interface Segregation Principle in your Unity3D projects. Create many small targeted interfaces instead of one large one so your code is cleaner and easier to reuse.

More Info: https://unity3d.college

Join the group: http://unity3d.group

β–Ά Play video
#

I'm pretty sure that's what you're looking for

glossy basin
idle oxide
#

How can I get data from a collided object. for example if I collide with an object it gets it's damage value (stored in an int) and saves it in some variable?

potent sleet
idle oxide
#

yeah I did that but I can't seem to find a way to get the variable out

potent sleet
heady iris
potent sleet
#

TryGetComponent
will attempt to get the Component(Script)
then put it in a variable you can use eg "healthScript"
then get your access that way.
variable should be public
but good practice is to make methods instead of directly changing vars imo
@idle oxide

verbal shadow
mental sigil
#

I am playing around with a small "tycoon style" 2D game in unity, where the player can place buildings that do things, thats the main idea, now I am not sure how to do this, I dont want to have everything on a grid so I want to be able to freely place the buildings, initially I just had a GameManager and a List of IBuildings that keep track of all the buildings that have been place but that seems just goofy, they should just be in the game and work without needing to be stored in a list

potent sleet
mental sigil
#

How do I keep track of my buildings without having them in a list?

#

I wnat to collision check when placing buildings for example

potent sleet
#

raycasts

#
  • boxcasts
mental sigil
#

Okaaaay, I have colliders on the buildign prefab

heady iris
#

I don't see a problem with having a list of buildings.

potent sleet
#

also yeah ^

#

is good for you to keep track of your buildings spawned or to be spawned etc..

mental sigil
#

Well sure the list itself is not bad maybe, but iterating all my building to check collisions seems stupid since there is already a collison system

potent sleet
#

yeah def don't do that

#

you'd have to keep track all bounds and rotations

#

it makes no logistical sense if you did that

heady iris
#

indeed

mental sigil
#

And also in that case, my buildings are GameObjects obviously but they also have the IBuilding interface that seems a bad pattern to me comign from C++ where I store IBuildings that are also GameObjects which is not visible

potent sleet
#

if(hit.collider.TryGetComponent(out IBuilding building))

#

though to check if things are "blocked" use a the other Physics functions

#

the bulk sized ones

#

and not rays

#

use rays mostly to find a spot on grid from camera pointer ig if its not a controller based

mental sigil
#

But with the IBuilings, I have the problem that if I store them az IBuildings then I could just add a new building into the list but they should all have game objects too

#

This feels goofy

heady iris
#

if a building is always on a GameObject, then make an abstract class that derives from MonoBehaviour

potent sleet
heady iris
#

that too: they can contain read-only information about buildings

mental sigil
#

so abstracty class not interface and I can make it always a game object

potent sleet
#

if its monobehavior it has all the access to gameObject is on

heady iris
#

it would, however, always be attached to a GameObject

cunning pivot
#

Hello how to deal with fps arm and gun not rotating vertically just horizontally, the gun has a parent called Weapon holder that is a child of the right hand of the player, also the player is animated

mental sigil
#

Thanks

potent sleet
idle oxide
cunning pivot
#
        _targetDirection = _playerInput.Player.Move.ReadValue<Vector2>().normalized;
        Vector2 _targetMouseDelta = new Vector2(_mouseLook.x, _mouseLook.y);
        _currentMouseDelta = Vector2.SmoothDamp(_currentMouseDelta, _targetMouseDelta, ref _currentMouseDeltaVelocity, _mouseSmoothTime);
        _xRotation -= _currentMouseDelta.y * _sensitivityX;
        _xRotation = Mathf.Clamp(_xRotation, -75, 75);
        _mainCamera.localEulerAngles = Vector3.right * _xRotation;
        transform.Rotate(Vector3.up * _currentMouseDelta.x * _sensitivityY);
heady iris
#

or use kinematic rigidbodies, so that they aren't affected by physics.

cunning pivot
heady iris
#

of course, in that case, you'll need to control the movement yourself

potent sleet
cunning pivot
#

if i parent the gun holder to the camera then the weapon rotates vertically with the camera but that leaves the hand and also the gun wouldn't position and rotate correctly with the hand

#

how do games handle that

glossy basin
#

Hello there, I am struggling to understand the implementation of this event, I want to subscribe to an event from my player health controller to my game manager script and then call a function inside of the event manager once this event is triggered.

So this is how I am defining my event

public class GameManager : MonoBehaviour
{
    public event Action OnHealthDamage;

 public void NotifyHealthDamage ()
    {
        Debug.Log("damage dealt");
        hitCrosshairAlpha = 1;
        inQueue += 1;
    }
}
#

And on my health controller I subscribe to that event, but my question is, how do I trigger NotifyHealthDamage once that event happens?

potent sleet
cunning pivot
glossy basin
# cunning pivot 1 sec

In my case I made a GameObject that contains the mouse look script (camera) and inside of it I placed the weapon manager that contains all of the weapon models

glossy basin
vivid remnant
#

Hello!

So I have a weapon system that I want to improve but I'm not sure how to go about it in a way that would also keep the code clean.

I have a base class called "Weapon" in which I keep all the common properties and behaviors of a weapon and two other classes that inherit from it: WeaponHitScan and WeaponProjectile. WeaponHitScan uses raycasts in order to simulate bullets being fired and WeaponProjectile instantiates physical projectiles that detect collisions.

My problem is with regards to the way this weapons can fire. I want both hit scan weapons as well as projectile based weapons to be able to fire one shot at a time(suited for revolvers, pistols, rifles, machine guns, etc.) or multiple projectiles at once(suited to shotguns).

I know how to implement the methods that can simulate accuracy and spread but I'm not sure where should I place them in order to make sure I can create hit scan weapons and projectile based weapons that can fire in any of these two ways.

Any advice would be appreciated. Also, please let me know if you need more details. :)))

cunning pivot
# glossy basin

ok but how do you manage to make the animated arms of the player move vertically with the camera too

glossy basin
potent sleet
# glossy basin

I think you can only Invoke an event from the class declaring

cunning pivot
potent sleet
cunning pivot
potent sleet
#

I'm not 100% on that just verify that

glossy basin
mental sigil
#

I have added this to my building script to check if it is colliding (via its interface)
But I get two things, first, it is always colliding and second I get this error in the console, if I remove the event functions it goes away

potent sleet
#

you dont invoke from another class

glossy basin
potent sleet
#

usually in OnEnable or Start

#

yes

#

but when are you subscribing

glossy basin
#

But now, inside the manager script, how can I trigger a function / bind a function to that event

#

Ahhh wait

potent sleet
#

thats what this does

glossy basin
#

Invoke should work

potent sleet
#

wdym takeDamage gets called every time you Invoke OnHealthDamage

glossy basin
#

Nvm, I dont get it

potent sleet
#

it's very simple

#

like Youtube, you subscribe to a channel you want notifications from

#

+= subscribe to event

glossy basin
#

What Im looking for is subscribing to an event, and performing the logic on the game manager script, not the health script

potent sleet
#

NotifyHealthDamage () is already doing that

#

put a method call in there?

#

i don't understand

#

what is your use case exactly cause is not making sense to me what ur doing

#

no reason to sub to your own event.

#

unless ur a child class or something

glossy basin
#

I am probably missunderstanding how events work, I will show pictures to better represent what I want to do

#

So this is inside my game manager class, this is the function I want to be performed once that event is triggered

#

and from the health class, I want to subscribe to that game manager event and trigger it whenever takeDamage happens

glossy basin
potent sleet
glossy basin
potent sleet
#

you want TakeDamage inside of health to do NotifyHealthDamage ?

#

so event should fire from Health script

#

then manager subs to it

potent sleet
#

yeah so its backwards lol

#

define event/ and invoke event, inside of health script

#

subscribe from Manager

glossy basin
#

That makes complete sense, let me try

#

But considering there can be multiple players, how would I subscribe to that then?

potent sleet
glossy basin
#

Ahhh, so there is no other way to that

potent sleet
#

like foreach(var healthScript in playersList)
healthScript.OnHealthDamage += HealthChangeNotify

#

ideally you can send the info of Who sent it as well if you add that in your Action

#

like Action<PlayerHealthScript> or just Player

glossy basin
#

Yup, I get your point

#

Thanks for your help!

potent sleet
mental sigil
#

I actually dont understand, I have added a rigid body and a collider to my buildings and I am listening to the OnCollisionSaty2D event to chekc if I can place a new building, (when trying to place something, I create a new GameObejct that follow the cursor position) but I never recieve the event even when I am hovering over an existing building

#

This code is not terribly complex with a lot to go wrong...

#

I know that it is not functional because if I ever once collide it will always fail

#

But it NVER fails as is

#

I started with enter/exit s but I was like maybe this is simpler for debugging

#

But nope, never get the event

#

Every building has a static rigidbody2d and a box collider2d

#

This is the collider and rigidbody on the prefab

timber jewel
#

What is the best way to learn csharp? Is it those long course videos on YouTube smth else. I followed brackeys 8 episode series for the beginner stuff but now don’t know what to do

potent sleet
#

get down and gritty to logic only without worrying about UI distractions

timber jewel
#

Ok thanks

potent sleet
dusk apex
carmine orbit
zinc igloo
#

am i doing something wrong here, i made a flappy bird like game and i want to make it so when the bird goes off the screen at y=17 then the game ends and it restarts, i dont get it am i doing something wrong (ps. theres no error code when going off screen)

gray mural
#

have you realised that this is a complicated issue?

hasty haven
#

Seems like a prety dumb/generic c# question but how would you all do this, use regex maybe?
I have some text blocks like "Press [Keybind] to do something" where I want to replace text within the square brackets with some other strings.
How would you all go about isolating/replacing bracket contents, even in cases where you have "][" or other potential invalid bracket pairs.

#

Feels like a simple interview question lol

heady iris
#

well, there's stuff like string interpolation and composite formatting

hasty haven
#

Sure, a lot of these messages are in the game on inspectables.
I already have the string values looked up from user settings.
I just want to replace the inner text

gray mural
#

like:

bla,bla,bla => bla bla bla
a:b:c => a..b..c
hasty haven
#

Sure just a sec

#

Input text example string
inputText = "Press [VoiceProx] to use proximity chat" where VoiceProx is a key that i use to get an actual button name from in settings
That comes from InputHandler.TryGetKeycode(string keybindName, out Keycode actualButtonCode)
I want to replace the bracket contents with whatever string contents it has

#
private string GetFormattedText(string inputText) {
    if(inputText.Contains('[') && inputText.Contains(']')) {
        //=> Replace keybinds with mapped button names
        
        return formattedText;
    }
      else return inputText;
  }
#

The first block is true even if theres '][' which I dont like

gray mural
#

I still don't get it

#

example?

#

what should this return?

GetFormattedText("Press [VoiceProx] to use proximity chat");
hasty haven
#

the output would be "Press [V] to use proximity chat" where input would be "Press [VoiceProx] to use proximity chat"

hasty haven
#

VoiceProx is a key that I use to say "Hey inputHandler, what button does the user use for VoiceProx?"

#

PlayerSprint could be a code, inputhandler returns "LeftShift"

mossy snow
#

why check for the brackets at all? Just go through your entire list of mappings and text replace

hasty haven
#

I suppose that would work

gray mural
#

I gon't get it anyways.

mossy snow
#

but why? You're doing a straight replace, regex is like using a golden hammer when a simple rock would do

gray mural
hasty haven
#

So theres only 13 keybinds so the sample size is relatively small

#

this is only being called once when a message is loaded

#

Cant change binds while reading message

mossy snow
#

buddy, if he has the text "blah blah [REPLACE] blah" and he wants [REPLACE] to be something else, regex is a mega complicated solution when Replace will do

#
  1. take your input string
  2. loop over every possible mapping, and replace entries in the input string with the output mapping
  3. done
hasty haven
#

That should probably work,
I dont believe any of the text could get replaced since the button codes are unique

mossy snow
#

exactly

buoyant crane
hasty haven
#

I could maybe append a symbol in front like $ for inline string arguments

#

replace $ + code

gray mural
#
private string GetFormattedText(string inputText) 
{
    string replacePattern = "[replaced]";

    string replacedText = Regex.Replace(inputText, @"\[.*?\]", replacePattern);

    return replacedText;
}
hasty haven
#

Id like to use that but these strings are defined in the inspector using a tool i made for non-programmer teammates

gray mural
mossy snow
gray mural
#

what's wrong?

wind palm
#

You then can match the Regex, use the group "key" for your dictionary etc and then replace the whole of the replace group

sharp oak
#

Hello! I assume this is a coding issue but I could be wrong. I coded a movement system for my 2D game. I made a map but whenever I press S to move my character, he just goes through the floor rather than walking "on it". What could the issue be?

gray mural
#

can you show code?

sharp oak
#

Sure, I also used the Unity Input Actions movement package too.

#

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

public class PlayerMovement : MonoBehaviour
{
private Vector2 movement;
private Rigidbody2D rb;

private void Awake() {
rb = GetComponent<Rigidbody2D>();
}

private void OnMovement (InputValue value) {
movement = value.Get<Vector2>();
}

private void FixedUpdate() {
rb.MovePosition(rb.position + movement * Time.fixedDeltaTime);
}
}

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.

sharp oak
#

Do you want me to send the hastebin.com file over with my code in it?

gray mural
#

oh wait

#

no

#

I mean with 3 `

#
public class PlayerMovement : MonoBehaviour
{
   private Vector2 movement;
   private Rigidbody2D rb;

   private void Awake() {
        rb = GetComponent<Rigidbody2D>();
   }


   private void OnMovement (InputValue value) {
        movement = value.Get<Vector2>();
   }

   private void FixedUpdate() {
        rb.MovePosition(rb.position + movement * Time.fixedDeltaTime);
   }
}
#

do both your character and the floor have non-trigger colliders? @sharp oak

sharp oak
#

Yes

gray mural
#

can you show them in Inspector?

sharp oak
#

Unless the difference is the issue. The floor has a Box Collider and the character has a Box Colldier 2D.

#

Also, yes, let me do that.

hasty haven
#

Okay I basically went with @mossy snow solution

private string GetFormattedText(string inputText) {
    // Format text only if potential bracket pairs detected
    if(inputText.Contains('[') && inputText.Contains(']')) {
        string formattedText = inputText;
        // Replace any key codes contained within square brackets
        foreach(string keybindName in System.Enum.GetNames(typeof(KeybindMnk))) {
            formattedText = formattedText.Replace("["+keybindName+"]", 
                                                  "["+InputHandler.GetKeyCode(System.Enum.Parse<KeybindMnk>(keybindName)).ToString()+"]");
        }
        return formattedText;
    }
    else return inputText;
}

InputHandler.GetKeyCode(KeybindMnk keybind) is where the true button name comes from
I included brackets in the replace.

Not the most elegant solution but it seems to work

#

Its not called rapidly and the input size is never huge

gray mural
gray mural
gray mural
sharp oak
#

Well, I made the map 3D but am trying to play it 2D.

#

Which probably wasn't too smart lol

mossy snow
# hasty haven Okay I basically went with <@155166991408168960> solution ```C private string Ge...

you still those unnecessary bracket checks, and made it harder to read

private string GetFormattedText(string inputText) {
    foreach (var binding in Enum.GetNames(typeof(KeybindMnk)).Select(kb => $"[{kb}]")) {
        var replacement = "$[{InputHandler.GetKeyCode(System.Enum.Parse<KeybindMnk>(keybindName)).ToString()}]";
        inputText = inputText.Replace(binding, replacement);
    }

    return inputText;
}```
gray mural
sharp oak
#

I had watched a video and in the video the person had said that you could make me the map 3D but still make the game 2D

#

Is there any way for me to change the map to 2D without having to rebuild the entire thing?

hasty haven
buoyant crane
mossy snow
buoyant crane
#

if you want them to interact with each other, they have to use the same type

sharp oak
#

But if I use 2D colliders on the 3D floor, I can't change it on the Z Axis, which means it won't cover the entire floor?

hasty haven
#

Thanks @mossy snow, you're getting a promotion

buoyant crane
sharp oak
#

I have a 3D map with a 2D character. And whenever I go into the camera and press play, he will go straight through the floor.

sharp oak
#

In the component section is it called 3D collider or Box Collider?

buoyant crane
#

box collider

buoyant crane
#

which should just be called Rigidbody

dusk apex
tropic quartz
#

Worth noting that if you have bumps on the ground, a box collider can easily get stopped by them because it's not rounded at the bottom, so it won't slide over them easily.
But in a flat game a box is super efficient for sure.

sharp oak
#

Well in doing of that, my character fell straight through the floor and now I have a ton of errors. Since my movement code was set to RG2

buoyant crane
buoyant crane
buoyant crane
sharp oak
#

First one is the floor and second one is the player.

buoyant crane
# sharp oak

disable the script for a sec, and see if it still falls through

sharp oak
#

I cannot play unless I fix the errors.

#

I do apologize to you guys, I don't have much knowledge have this stuff.

somber nacelle
#

You probably need to reassign the rb variable of the 'PlayerMovement' script in the inspector

sharp oak
#

That's what I thought, but that option is greyed out

buoyant crane
somber nacelle
sharp oak
#

Normally you would put Rigidbody2D in the script then drag the Rigidbody2D into the settings of the script in the Inspector. But since I don't have a Rigidbody2D, I don't know what the line of code is for the 3d version. And same with the Vector. It used to be Vector2 but that isn't working anymore.

sharp oak
somber nacelle
#

can you show your code and what the inspector for the object looks like?

#

also the 3d rigidbody is literally just Rigidbody which you can clearly see in your previous screenshot that shows a rigidbody component and also has a convenient (?) button that takes you to the docs for it

sharp oak
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerMovement : MonoBehaviour
{
   private Vector2 movement;
   private Rigidbody2D rb;

   private void Awake() {
        rb = GetComponent<Rigidbody2D>();
   }


   private void OnMovement (InputValue value) {
        movement = value.Get<Vector2>();
   }

   private void FixedUpdate() {
        rb.MovePosition(rb.position + movement * Time.fixedDeltaTime);
   }
}
somber nacelle
#

but also this object clearly does not have a Rigidbody2D on it so that is why you were getting the errors

sharp oak
#

Exactly, but whenever I change Rigidbody2D to just Rigidbody, I still get errors.

#

One of the errors says something about Vector2 being wrong.

somber nacelle
#

well yes, MovePosition expects a Vector3 not a Vector2. you will need to create a Vector3 from the movement vector so you can put the Y axis into the Z axis

#

this is all beginner stuff, there are beginner unity courses on the unity !learn site if you are not familiar with this

tawny elkBOT
#

πŸ§‘β€πŸ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

sharp oak
#

Besides that, unless the guide covers it, is there a way to completely change my map to 2D, or is the only way to do that to rebuild it?

cunning pivot
#

@glossy basin @potent sleet sorry to disturb you but just wanted to say thank you for the guidance, the solution was IK now even when i turn the camera up it works nice

glossy basin
#

Glad you got it working

#

Hello there, I guess this is kind of a beginner question, but how can I use a coroutine on a class that derives from an abstract class of type ScriptableObject?

#
public class ChargeWeaponPreset : WeaponBase

I have this class, where I want to use something like StartCorotine(Coroutine()); but since the base class is of type Scriptable Object, I cant do that

#

This is my base class

public abstract class WeaponBase : ScriptableObject
wind palm
glossy basin
#

How can I let my manager know that it has to start that coroutine

buoyant crane
wind palm
#

So if you have a class that has a public static instance of MyClass that extends Monobehaviour, you'd just do MyClass.Instance.StartCoroutine

#

Then any SO can use the same GO

glossy basin
#

I guess I could use my weapon manager class to do that

wind palm
#

Otherwise (as an example) your armour would need a separate one that's exactly the same, or call on your weapon manager for it.

#

Which makes no sense

honest edge
#

sound like a great place for the command pattern here. leave the command base class handle the coroutine and just use them from anywhere.

glossy basin
glossy basin
honest edge
#

check the one from Jason like the one I sent earlier today. You'll see how you can apply this specific case to it

#

and unbound these things from the code itself but just creating instance of the command and executing them. The execution is then handled outside of the class you want to call it from (Thecoroutine in this case) and run in your commands instead.

wind palm
#

Sounds very over engineering for needing to call one method on a Monobehaviour xD

languid hound
#

Is there anywhere I can learn how to get the stack trace from a crash dump file?

honest edge
#

that's always up to the use case. we have no context on how reusable this needs to be here. could be

vagrant pelican
#

isnt there anyone to help me with creating a 3d steering wheel controller pls

woven crystal
#

Hello. I've got some issues with my character movement.

Currently using a fixed upate to move my character.
I have an issue where my character suddently stops moving then sort of teleports forward with a jittery movement.

You can see in the video from 0:03 - 0:04 seconds the player stops briefly then appears to teleport a bit in a jittery movement.

I've tried to enable interpolate but doesnt seem to fix the issues.
Help would be appreciated!

Here is my code and the video to show it.

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

public class IsometricPlayerMovementController : MonoBehaviour
{

    public float movementSpeed = 1f;
    public LayerMask solidObjectsLayer;
    public LayerMask interactableLayer;
    IsometricCharacterRenderer isoRenderer;
    //private PlayerInput playerInput;
    private PlayerInputActions playerInputActions;

    private Rigidbody2D rbody;

    private void Awake()
    {
        rbody = GetComponent<Rigidbody2D>();
        isoRenderer = GetComponentInChildren<IsometricCharacterRenderer>();
        //playerInput = GetComponent<PlayerInput>();
        playerInputActions = new PlayerInputActions();
        playerInputActions.Player_World.Enable();
    }


    // Update is called once per frame
    void FixedUpdate()
    {
        Vector2 currentPos = rbody.position;

        Vector2 inputVector = playerInputActions.Player_World.Movement.ReadValue<Vector2>();
        inputVector.y = inputVector.y/2;
        /*
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");
        //fixes diagonal movement on isometric scene 
        if(horizontalInput != 0 && verticalInput != 0)
        {
            verticalInput = verticalInput/2;
        }
        Vector2 inputVector = new Vector2(horizontalInput, verticalInput);
        */
        inputVector = Vector2.ClampMagnitude(inputVector, 1);
        Vector2 movement = inputVector * movementSpeed;
        Vector2 newPos = currentPos + movement * Time.fixedDeltaTime;
        isoRenderer.SetDirection(movement);
    
        rbody.MovePosition(newPos);

    }


}
honest edge
#

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

knotty sun
knotty sun
#

yes and cache the values for use in FixedUpdate

woven crystal
#

Well I hope that fixes the issue im having

#

oh wait no

#

thats the old unity input system

#

i commented that out actually

#

@knotty sun

dusk apex
#

The section looks commented out.

glossy basin
#

You are doing the same with the new input system there

knotty sun
#

indeed, sorry I missed that, same applies for new input system though

woven crystal
#

So what specificlaly should i replace and put in update?

#

Vector2 inputVector = playerInputActions.Player_World.Movement.ReadValue<Vector2>();
inputVector.y = inputVector.y/2;
inputVector = Vector2.ClampMagnitude(inputVector, 1);
Vector2 movement = inputVector * movementSpeed;
Vector2 newPos = currentPos + movement * Time.fixedDeltaTime;

#

this entire part?

dusk apex
#

The hiccup honestly looks like low frame rates where a teleport occurred due to fixed update occurring more than once.

glossy basin
#

Vector2 inputVector, cache this globally, set the value in Update

#

and use it in FixedUpdate

dusk apex
#

Projected path and position looks correct.

woven crystal
#

its honestly getting annoying cuase it def occurs more than once

dusk apex
#

Not sure what there is to fix. Profile your application and see if it's really a delay there.

woven crystal
#

I ran the build and the issue still persists

honest edge
#

fixedupdate can occur 0 to many times per frame. Usually use for physics based stuff. Any input might not be read here.

woven crystal
#

I had thought it would be an editor issue so I ran several builds

#

But still has this issue

dusk apex
#

I think the teleporting is the concern here rather than input lag.

woven crystal
#

Yeah.

#

I just cant seem to fix that random stop and then teleporting foward outta nowhere

honest edge
woven crystal
#

it would be okay if it happens once, but it happens like once every 10 seconds? sometimes more

wind palm
wind palm
woven crystal
#

I'd be more than happy to compile my project and send a zip file

#

for you to play around

#

@wind palm

#

This things been driving me nuts as I've been trying to fix a lotof things

wind palm
#

Yeah, I don't run .exe files from discord

woven crystal
#

Turning interlpolate on and off/ messing with the physics stuff

wind palm
#

Not that I think you're up to no good.

woven crystal
#

Oh.... welp

wind palm
#

Profiling is the best way to see where the issue is.

dusk apex
#

Between 3 to 4 in the video, the character makes a slight jump. This likely occurs because draw frames were missed but physics frames still accounted for the delay (teleport). You could either not move accurately and in Update with some max distance threshold or accurately as you've got it with a teleport visually shown. This implies that there is really a frame delay. Use the profiler to ensure that's the issue.

woven crystal
#

Is there a way I can share the profiling results?

#

Not really sure how to read the profiling results

#

But I do notice that whenever the teleport issue occurs theres a spiek of some sort

wind palm
#

There are tons of guides online that'll do a better job than a text based chat

wind palm
#

It looks like the garbage collector

#

If it's the dark green mostly

#

Looks like it on my phone.

#

You need to be careful with allocations.

glossy basin
#

Agreed, looks like GC collection

pure dragon
#

is using public dynamic Execute(){} when using the Command Pattern system bad practice if I want to return a variable to the commands caller?

glossy basin
#

I suggest you enabling deep profile and track down where the excesive GC is happening

wind palm
pure dragon
knotty sun
#

since when did unity even support the dynamic keyword?

mossy snow
ashen yoke
#

replace with object casts if you cant resolve types at compile time

wind palm
ashen yoke
#

dynamic has roughly same performance as reflection

mossy snow
#

dynamic is also not supported on some platforms that don't allow code jitting, that's the main reason to avoid here

ashen yoke
#

and not "get meta once reuse later" but do it all over at every call performance

wind palm
pure dragon
#

i see

wind palm
#

Gives you less leg room to do other graphical "stuff".

pure dragon
#

in what way would I be using delegate by the way? like a public delegate int Execute(){} or something?

wind palm
#

If you have a ICommand interface, that would be so much better.

ashen yoke
#

you can use out params, you can use closure

#

but yeah type system is better

pure dragon
pure dragon
ashen yoke
#
object b = new object();
Action a = () => {
  int i = 5;
  object obj = b;
  print(obj);
}
#

is this a command?

pure dragon
#

but that would pass by reference not by value right?

ashen yoke
#

only structs are passed by value

#
class Command<T>
{
    private Func<T> del;
    public Command(Func<T> del)
    {
        this.del = del;
     }

     public T Execute() => del?.Invoke();
}
Command<int> icmd = new Command<int>( () => 
{
    MySystem ms = GetSystem<MySystem>();
    float time = Time.time; 
    ms.PrintTimeBetweenCommandCreationAndExecution(time, Time.time);
});
#

is this close to what command pattern does?

cursive moth
#

Hi, I created a simple tool for mass renaming stuff but the problem is that it adds a 1 for each selected object.
Is there a way to prevent it from running for each selected object or do I have to write a different piece of code?

using UnityEditor;
using UnityEngine;

namespace Assets.NNR.Editor
{
    public class MultiObjectRename
    {
        [MenuItem("GameObject/Rename Selected Objects", false, 0)]
        private static void RenameSelectedObjects()
        {
            int objectCount = Selection.objects.Length;
            if (objectCount < 2)
                return;

            Undo.RecordObjects(Selection.objects, "Multi Object Rename");

            for (int i = 1; i < objectCount; i++)
            {
                GameObject selectedObject = Selection.objects[i] as GameObject;
                if (selectedObject == null) continue;
                selectedObject.name = Selection.objects[0].name + " " + (i + 1);
            }
            Selection.objects[0].name += " 1";
        }
    }
}

What would also be nice is opening up a dialog where you could enter a name but I wasn't able to figure out how to do that :/

cursive moth
dusk apex
#

Keep a copy of the original name and add the value to the end.

pure dragon
cursive moth
dusk apex
#

Assuming the name of the object selected is simply concatenating numbers to itself

cursive moth
ashen yoke
#

and you can use some factory if you need reusable commands

#

or you can mix the two, and have a generic command with a closure in it

pure dragon
woven crystal
#

He has no issue walking for 10minutes

#

He also had his profiler on and we didnt see any spikes

dusk apex
wind palm
#

Your issue is GC though.

#

You need to look into it.

dusk apex
#

Where the final name is that of the object at index 0 with an extra index numeric that you're concatenating.

leaden ice
woven crystal
#

He walked around for 10min and we couldnt find any issue

#

GC wouldnt just happen jsut to my pc right?

cursive moth
wind palm
cursive moth
wind palm
#

Perhaps theirs is just faster

woven crystal
wind palm
#

For instance if you're using raycasts make sure you're using the nonalloc versions.

dusk apex
# woven crystal GC wouldnt just happen jsut to my pc right?

Garbage Collection happens if you're allocating and freeing memory (no longer referencing memory). Depending on computer/device hardware, you may or may not feel the impact. It's likely there though if you're both running the same application.

wind palm
#

Arrays can be expensive too if used improperly.

woven crystal
#

Only arrays for direcitonal facing

wind palm
#

Then you've got issues with other elements in your code

woven crystal
#

static arrays

wind palm
#

Static arrays are ok as look as you're not recreating them

woven crystal
#

Theres really only one other script that is being used to sort isometric sorting

wind palm
#

If I did new int[1024] every update it'll have an effect

woven crystal
#

Nah we arent recreating them. Theyre just used to store the directions the player will face

cursive moth
wind palm
dusk apex
#

I'm on mobile and am assuming GC was kicking a fuss.

leaden ice
#

You can do whatever you want

cursive moth
leaden ice
#

Wrong

cursive moth
#

you'll end up with Item 1 1 1 1 1 2

leaden ice
#

Not if you actually save the unnumbered string in a variable that is unrelated to the object

#

And reuse it

cursive moth
#

how can I do that tho?
If I do it inside of that function it'll just get called for each object and I'll end up with the same thing that I have rn

leaden ice
#

$"Item {n}"

#

Pretty much all you need

cursive moth
#

ik what string interpolation is and how to use it, I don't see how that'll solve my problem

woven crystal
dusk apex
#

If the function is called for each item, you wouldn't need the for loop. Just a variable.

woven crystal
#

Any specific way to figure it out?

leaden ice
#

Without ever changing the originalName variable

cursive moth
wind palm
cursive moth
#

if you do it inside of the Rename Objects function it'll get called for each object and you'll end up with the same thing I have rn

cursive moth
leaden ice
dusk apex
cursive moth
dusk apex
#

That isn't the issue though. Issue is that somewhere along the line, the for or if statement actually becomes valid and concatenates the name of the first element (which had a bunch of ones) plus index to each element.

#

I give up.

cursive moth
cursive moth
#

it's not the for loop that's causing the issue with the said approach

cursive moth
vagrant pelican
#

Δ° need a 3d steering wheel controller script but i dont know how to make it the AI and YouTube cant help me

#

Can you help me doing it

lean sail
#

before you make it AI, do you have a script that works based on your input?

cursive moth
lean sail
vagrant pelican
#

Δ° can only rotate my steering wheel when i presses a key to the left and when pressed d key to the right

cursive moth
lean sail
#

i didnt see the original problem, its far up

vagrant pelican
#

Like ETS 2 game

cursive moth
# cursive moth this is kind of a workaround but not really because it requires you to add a 1 a...

The first one I sent renames all the objects with additional 1s for each selected object.
I've made a workaround which does work but requires you to add the 1 to the end of the 1st object's name(I'll reply to that message).
I am asking if it's possible to run the said function only once no matter how many objects are selected or have some other workaround which doesn't require you to add a 1 to the end of the first object's name.

#

In case you missed it, it's an editor script which you access with the right click menu:

lean sail
leaden ice
# cursive moth here:

All you need is like:

for (int i < plantBar.transform.childCount) {
  plantBar.GetChild(i).name = $"Plant Slot {i}";
}``` no?
lean sail
cursive moth
#

I don't want it to be called item, it is a script which is supposed to work with any name you input as the name of the original object.
At first, I wanted to have a dialog that would accept a string as an input for the base name but I couldn't figure out how to do that so I settled with this.

lean sail
#

can you explain the actual goal? because everything im reading seems like im missing some massive context. Without this context, it seems like u just dont know how basic c# works or loops

leaden ice
cursive moth
leaden ice
#

You could use a dialogue too if you want

#

To enter the unnumbered name

leaden ice
#

You can't just assume the name has a number or that the last character is a number or something

#

Your code would have to check

cursive moth
# leaden ice Your code would have to check

I am well aware of that, the problem is that at the very end of what you are suggesting I'd have to change that object's name to Item 1 from Item and end up with the exact same thing

lean sail
#

im probably missing too much context, this sounds like a complete beginner problem to me where u just use an if statement to check if its 1

cursive moth
leaden ice
#

Basically that just means looking for and removing any numerical characters and whitespace from the end

cursive moth
leaden ice
#

No

#

Again

#

It doesn't matter

leaden ice
#

And replace the hard coded string for your parsed object name

#

Without the number

leaden ice
honest edge
#

Sounds to me like it's just a matter of parsing the thing and removing any numerical character and going from there.

cursive moth