#archived-code-general

1 messages ยท Page 138 of 1

leaden ice
#

the TMP_Text part isn't really relevant

gray mural
#

yeah, substring and IndexOf sound quite easy

#

I mean

leaden ice
#

You could also use regex if you were so inclined

gray mural
#

is there any possibility to remove TMP_Text's line itself?

eager yacht
#

maxVisibleLines

leaden ice
#

^ won't actually change the string though

#

nor will it change the layout

gray mural
leaden ice
#

it will not change the .text value

#

just what is displayed

gray mural
leaden ice
#

When I say "it" I mean what Nom mentioned

#

if you want to actually change the text, you have to actually change the text

gray mural
#

thanks

#
if (_textComponent.textInfo.lineCount > _textComponentLineCount)
{
    string lastWord = _textComponent.textInfo.wordInfo[^1].GetWord();

    //text = text.Substring(0, text.Length - lastWord.Length - 1);

    textComponentIndex += 1;

    text = lastWord;

    print("new textComponent added");
}
#

what's wrong here?

#
NullReferenceException: Object reference not set to an instance of an object
TMPro.TMP_WordInfo.GetWord () (at Assets/#Scripts/Builtin/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMPro_MeshUtilities.cs:195)
TMPro.TypingField.Update () (at Assets/#Scripts/Helpers/TypingField.cs:156)
leaden ice
#

which line is 156

gray mural
limber agate
#

_textComponent is prolly null

leaden ice
#

you'll have to break that line down and figure out which piece is returning null

limber agate
#

Or something else in there

#

Debug it

eager yacht
#

Probably wordInfo or wordInfo[^1] is null

leaden ice
#

but I would guess textInfo isn't guaranteed to have a wordInfo or something

gray mural
gray mural
#

that's strange

gray mural
#

wordInfo[^1] does not have textComponent

#

it sounds like I need to find it manually

leaden ice
gray mural
#

I think I should

string lastWord = text.Split(' ')[^1];
leaden ice
#

since it's going to allocate a ton of strings and an array

#

only for you discard almost all of it

leaden ice
#

whatever you want to split on,yeah

gray mural
#

so last word

#
string lastWord = text[(text.LastIndexOf(' '))..];
leaden ice
#

more like

eager yacht
#
_text.ForceMeshUpdate(true);

var textInfo = _text.textInfo;

Debug.Log($"{textInfo.wordInfo.Length} vs {textInfo.wordCount}"); // 32 vs 18

var lastWordA = textInfo.wordInfo[textInfo.wordCount - 1];
var lastWordB = textInfo.wordInfo[^1];

Debug.Log(lastWordA.GetWord()); // fdsajfdsfdsfsdasfd
Debug.Log(lastWordB.GetWord()); // inner usage gets null data, so exception
leaden ice
#

unless this works to get a substring text[(text.LastIndexOf(' '))..]; but that looks like Python not C# to me ๐Ÿ˜ฎ

gray mural
#

works almost like substring

#

but range

#

string[(from index)..(to index)]

leaden ice
#

interesting, newer syntax I haven't used I guess

#

either way

gray mural
gray mural
#

it works with arrays too

#
int[] bla = foo[2..];
leaden ice
#

I mean it's a feature of the indexer operator itself it seems []

wide terrace
#

neat discovery ๐Ÿ‘€

gray mural
leaden ice
wide terrace
gray mural
eager yacht
#

Slicing creates a new array ๐Ÿ˜”. Can use a span to have a range inside the existing array instead.

int[] slice = arr[2..]; // new array
Span<int> span = arr.AsSpan(2..); // slice over existing array
gray mural
#

you can also resize array btw

public static void Resize<T>(ref T[] array, int newSize);
eager yacht
#

Which is kind of a naming lie, since it doesn't "resize" the actual array. It makes a new one of the length and does a buffer copy to the new one.

lean sail
#

well thats what resizing an array is regularly

gray mural
regal oak
#

I don't understand.. I touch the gem, and nothing happens

public class PlayerController : MonoBehaviour
{
    public float speed = 5f;
    private Rigidbody playerRb;
    private GameObject focalPoint;
    public bool hasPowerUp = false;

    // Start is called before the first frame update
    void Start()
    {
        playerRb = GetComponent<Rigidbody>();
        focalPoint = GameObject.Find("Focal Point");
    }

    // Update is called once per frame
    void Update()
    {
        float forwardInput = Input.GetAxis("Vertical");

        playerRb.AddForce(focalPoint.transform.forward * forwardInput * speed);
    }

    private void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag("Powerup"))
        {
            hasPowerUp = true;
            Destroy(other.gameObject);
        }
    }
}
lean sail
#

cause u said last line, but this is last word

wide terrace
regal oak
wide terrace
eager yacht
# lean sail well thats what resizing an array is regularly

Yeah, you'd just be surprised at the amount of people that think that arrays can actually change their own immutable length. Reminds me of people who don't realize that Lists are just arrays that copy into larger new arrays when needed, and instead think they are magically different. TT_laugh

lean sail
eager yacht
#

Sounds about right yeah

heady iris
gray mural
#

no, wait, actually

#

if there are no spaces

#

yeah.

#

that's true, I need \n

#

thanks

#

I realised it while typing

regal oak
#

Tutorial(image)
My image(with the bug)..
Why?

fervent furnace
#

ienumator is not ienumerable

gray mural
gray mural
#

TMP_Text does not have \n

#

it's not splited by new line

#

word's position is changed

fresh cosmos
#
static async Task unloadAsync(string SceneName)
{
    AsyncOperation operation = SceneManager.UnloadSceneAsync(SceneName);

    while(!operation.isDone)
    {
        UnityEngine.Debug.Log("unloading: " + operation.progress );
        await Task.Delay(1); // Which is better? Task.Yield(); or Task.Delay(1); ?
    }
}

static async Task enablePreloadedScenes(SceneCollection targetScenes)
{
    // ... some stuff such as setting adding scenes to List<string> UnloadScenes

    await scenesAreActive();

    Task[] unloads = new Task[UnloadScenes.Count];
    for (int i = 0; i < UnloadScenes.Count; i++)
    {
        unloads[i] = unloadAsync(UnloadScenes[i]);
        Debug.Log("unloading: " + UnloadScenes[i] + ": " + unloads[i].Status);
    }

    UnityEngine.Debug.LogError("never passes this await"); // none of the unload tasks ever gets completed as their progress is stuck at 0.0f
    await Task.WhenAll(unloads);

    // ... Rest of this async method
}

im having an issue where the AsyncOperation in the unloadAsync method never goes past 0 progress. im not entirely sure why this happens. can anyone give me some pointers?
the reason im doing it this way was i thought that i could let all the scenes load at the same time instead after each other like most tutorials do. Maybe there is a reason they do it that way?

lean sail
#

my mistake

gray mural
gray mural
#

@lean sail I think I have found the solution, just in case you are interested

string lastLine = text[_textComponent.textInfo.lineInfo[^1].firstCharacterIndex..];
#

oh, no, wait

#

forget it

#

that's so dump

#

no, wait

#

actually

#

it shouldn't return 0, right?

#

so yeah

#

it's correct

fresh cosmos
#

yep, that fixed it

regal oak
regal oak
uneven slate
#

Hello. I'm trying to figure out how to determine if an attribute is defined on a behavior or not (class or otherwise) to figure out if it's got a PunRPC on it or not.
Digging through MS's docs & stackoverflow suggests it should just be as simple as ArbitraryMonobehaviorType.IsDefined(typeof(PunRPC)), but that clearly doesn't work, otherwise I wouldn't be asking. In my case it always returns false, even when ArbitraryMonobehaviorType is a type that 100% has a PunRPC on one of it's methods.

Do I need to iterate through every method in the type and check that?

leaden ice
uneven slate
#

Gotcha. Figured as much but just wanted to make sure I wasn't doing something peabrained w/ isDefined ๐Ÿ‘

shy spire
#

I'm multiplying a normalized vector by the deltaTime, in editor it usually goes to 0.00XX decimal cases but in build it seems to get bigger, going to 0.0XX, which makes a later multiplication much bigger than it's supposed to be. Does anyone know why this happens?

leaden ice
#

That's the whole point of it

#

If that is breaking your code you have used it incorrectly

shy spire
heady iris
#

how do you know that?

#

do you have an FPS counter

wide terrace
#

Apparently not - at 60 FPS deltaTime will be roughly 0.0166... If it's 0.00XX in the editor, then the editor's framerate is in excess of 60 FPS

shy spire
heady iris
#

that doesn't mean you're running at 60 fps

#

it means you're running up to 60 fps

heady iris
leaden ice
#

Maybe show the code

#

And we can suggest a fix

shy spire
leaden ice
#

Stats window is false

#

Use the profiler and/or an actual framerate calculation from code

heady iris
shy spire
#

I'll see if I can source the info from somewhere else then

leaden ice
#

It's well known to not be accurate

fresh cosmos
#

in all the examples i have come across about UnityAction's they all just simply say doing this should work

UnityAction myAction;
myAction += someMethod;
// ... Later
myAction(); 
// or
myEvent.addListener(myAction);

but when i do this its telling me myAction is not set, which makes sense but i cant seem to get any valid constructor. what am i doing wrong?

swift falcon
#

can i actually cap fps in the editor?

leaden ice
fresh cosmos
shy spire
primal wind
#

I'm getting a weird wobbling on my on screen joystick when i hold it close to the center. Any idea what might be causing it? https://hatebin.com/tngakntihq

fresh cosmos
heady iris
#

when it's a serialized field, it'll get initialized by unity for you

#

i dunno about using it as a local variable. not sure why you'd want to do that :p

#

the main draw is having that nice inspector UI

fresh cosmos
#

im just experimenting with async methods, wanted to test if i could use an action instead of a completion event

#

as that would be easier to pass in through a method

#

but maybe there is a better way

#

i guess Task.continueWith() is similar functionality of what i was looking for by doing that

brittle nebula
#

So I have this problem where I have this client gameObject, but when using unitys netcode, for some reason the clients physics completely break when I try to use rb.Addforceatposition, addforce seams to work, but when I do atposition my client gameObject just glitches and flies all over the place. This doesn't happen to the one hosting the server

swift falcon
#

that's the issue i usually see, accidentally running code on both sides that applies to 1 object

brittle nebula
heady iris
#

that means that the client owns the transform

#

however, I'm not sure that Network Rigidbody expects that

#

use a Network Transform

brittle nebula
heady iris
#

what?

#

in what context?

brittle nebula
# heady iris in what context?

with rpc's I should be able to this, says the docs, but RequireOwnerShip just doesn't seam to exist cs [ServerRpc(RequireOwnerShip = false)] void PhysicsServerRpc()

brittle nebula
# heady iris typo

no not typo, intellisence doesn't show it to me and also I get error without typo

heady iris
#

where is ServerRpc coming from?

#

if you hover over it, you should see the full name

brittle nebula
#

nevermind I don't get an error intellisence was just a big dumbfuck and didn't let me autocomplete

brittle nebula
#

why is in this case is owner not working? the host can just move both players but the client can't move any cs private void FixedUpdate() { if (!IsOwner) return; PhysicsServerRpc(); } [ServerRpc(RequireOwnership = false)] void PhysicsServerRpc(){ //Moving player with addforceatpos.. . . . }

lean sail
shut elm
#

Hi, I made a 3D printer in a game and now I want to be able to actual "print" gameobjects. To do that i need to be able to cut gameobjects at a specific height to slowly display more of the gameobject. Any Ideas how I could do that?

brittle nebula
lean sail
brittle nebula
lean sail
# shut elm visual

I would just spawn the object in, and use a shader or something to slowly reveal it

shut elm
#

I don't know much about shaders, can I somehow control at which speed and when the shader reveals it using code?

lean sail
#

server rpc means the code runs on the server. Your player is not providing its own input

brittle nebula
#

hm, so it shouldn't be an rcp right?

lean sail
shut elm
#

thank you, you already helped me a lot <3

lean sail
wooden cove
#

I can't really seem to get the timing right on this coroutine. it seems to always run within a second, even with parameters different...
The animationTime variable is set to 3, which would lead me to assume 3 seconds pass before this animation finishes, but its taking one second and just waiting the remaining 2

    IEnumerator MoveInternal(GameObject moveTarget)
    {
        float currentAnimationTime = 0;
        _isAnimating = true;

        while (currentAnimationTime < animationTime)
        {
            var calculatedPosition = moveTarget.transform.position + new Vector3(0, GetComponent<MeshRenderer>().bounds.size.y / 2, 0);
            transform.position = Vector3.Slerp(transform.position, calculatedPosition, moveCurve.Evaluate(currentAnimationTime / animationTime));
            currentAnimationTime += Time.deltaTime;
            yield return null;
        }
        
        _isAnimating = false;
    }
#

for context, im trying to move a gameobjcet based on the properties of a curve over a timer

lean sail
#

also u might wanna at least cache some of those variables, GetComponent<MeshRenderer>().bounds.size.y i doubt this needs to run every frame

wooden cove
wooden cove
lean sail
wooden cove
#

the value of moveCurve.Evaluate appears to go from 0 to 1 over 3 seconds, which is expected

wooden cove
#

I forgot about that

#

that fixes the timer of the movement, now I just need to change it so it uses the Y value of the curve to make the character kinda jump up

#

I may not be able to use standard lerp for that and have to do it custom I tihnk tho?

brittle nebula
lean sail
wooden cove
# lean sail i dont think your curve specifically should be used for the vector. I guess u co...

I tihnk I figured out how it should function```cs
IEnumerator MoveInternal(GameObject moveTarget)
{
var calculatedPosition = moveTarget.transform.position + new Vector3(0, GetComponent<MeshRenderer>().bounds.size.y / 2, 0);

    float currentAnimationTime = 0;
    _isAnimating = true;

    var origPosition = transform.position;

    while (currentAnimationTime < animationTime)
    {
        var evalValue = moveCurve.Evaluate(currentAnimationTime / animationTime);
        transform.position = new Vector3(Mathf.Lerp(origPosition.x, calculatedPosition.x, currentAnimationTime / animationTime),
                origPosition.y + evalValue,
            Mathf.Lerp(origPosition.z, calculatedPosition.z, currentAnimationTime / animationTime));
        currentAnimationTime += Time.deltaTime;
        yield return null;
    }
    
    _isAnimating = false;
}
lean sail
#

you should probably split that up, for readability sake

#

but i guess if your curve determines the height the player jumps, then it should be fine

#

you can also cache the currentAnimationTime / animationTime so you arent calculating it 3 times

wooden cove
#

ya, now that it works. next step is to do some cleanup

#

I wanted to get that stuff working before I messed around with sorting it all out

amber depot
#

ok so i tried the awake function but it still calls the awake in the script attached to the Main Camera first and then the Game Manager where I state the singleton Pattern

leaden ice
#

note what I wrote about doing stuff that depends on other scripts in Start

amber depot
#

ohh yes my bad as start is called anyways after update

crimson atlas
#

if i first hold SHIFT (FineTurn bound key) then press A or D (Turn bound axis) it turns slowly alright
however if i first press A or D and then press SHIFT while holding A or D, it will continue to turn fast, disregarding FineTurn.
how can i fix that?

heady iris
#

apply the fine turn effect when rotating

#

you're doing it in Turn, which sets turnInput

#

so pressing or releasing shift while you're turning will do nothing

#

because turnInput can only change when you press or release the A/D keys

crimson atlas
#

rewrote it like this

public void Turn(InputAction.CallbackContext context)
    {
        turnInput = context.ReadValue<float>();
    }

    public override void Move()
    {
        fineTurn = playerInput.actions["FineTurn"].IsPressed();

        rigidbody.angularVelocity = turnSpeed * turnInput;
        if (fineTurn) rigidbody.angularVelocity *= fineTurnFactor;
        rigidbody.velocity = transform.up * moveSpeed;
    }

    public override void Start()
    {
        base.Start();
        playerInput.actions["Turn"].performed += Turn;
        playerInput.actions["Turn"].canceled += Turn;
    }
#

would there be a classier way of doing that?

heady iris
#

sounds reasonable to me

olive silo
#

is there a way i can build a cubemap from scenes at build time? i'd like to be able to have scenes specifically for creating some static skyboxes that are rendered from a camera placed inside them at compile time, that way i can reuse those textures as skybox cubemaps in actual levels.

#

i have no idea if something like this is possible. my current idea is to have a baking process you can initiate from within the game that cycles through each skybox scene, renders to a cubemap, and then saves the cubemap in some sort of persistent storage. i believe source does this for reflections, but per-level.

ashen yoke
#

completely possible

#

and rather simple, but tedious

#

you will have to sit there hardcoding in camera rotations for each side

#

since cubemap has specific rules for each face

olive silo
#

right, i see. i assume i could just save the render textures to the resource hierarchy?

#

or update existing ones, rather. that way it's easier to just set my skybox material to a known resource.

ashen yoke
#

you stamp them into a large one, large one you write with EncodeToPNG , dont remember exact name

olive silo
#

right i see. makes sense

ashen yoke
#

goes on disk, imports as normal image

olive silo
#

yeah that's what i was thinking i'd have to do

#

is there any way to automate this at build-time? or would i just have to, for example, have some debug state that lets me build skybox cubemaps?

ashen yoke
#

yes there is

olive silo
#

ah i see! thank you ๐Ÿ™‚

ashen yoke
#

that should be just a point you call your cubemap build

#

you probably need editor tooling for it to also update at edit time

#

you dont need a special state to do things like this, you can store the scene you are in, load cubemap scenes and build them with automation, and return to the scene you were in when its done, with EditorSceneManager

#

all that with a button press, is what i mean

wintry crescent
#

Is there a way to destroy gameobjects in onValidate in editmode? if I do Destroy, it screams that I must use DestroyImmediate in edit mode as Destroy is not supported, and when I try to do DestroyImmediate, it screams it can't do DestroyImmediate in OnValidate, and I must use Destroy
I'm at a bit of a loss

wintry crescent
ashen yoke
#
EditorApplication.delayCallback += () => DestroyImmidiate(gameObject);
solemn raven
#

hi ,
1 - is it possible to get image's material with all the CURRENT settings ( ex: if color was red then I should get color="red";) ??
2 - is it possible to not just get the material but read it as a text ?

ashen yoke
#

UI.Image?

solemn raven
#

yea

ashen yoke
#

do you use custom material on the image?

#

by default color is the vertex color of the mesh

solemn raven
#

no, I was just playing around with image and I thought of those two questions , tried to search them myself but i couldnt find an answer

#

not that important

ashen yoke
#

default behavior is when you set image.color the image mesh generator sets all vertices to that color

#

which is later rendered by ui shader

#

so you cant technically get the color from the material since it doesnt use it

#

as for getting material properties, if image/graphic class allows you to get internal material through material property, you would have to iterate all material properties and write those strings yourself

solemn raven
rugged storm
#

yo is there a way to make visual studio break on exception? in specific a IndexOutOfRangeException

#

im trying to debug but its happening inconsistently, reqired input and on something that runs multiple times each frame so I need it to only break if an exception actually occurs

lean sail
#

actually u can set conditions on breakpoints, but u need to know whats actually causing the error

rugged storm
#

ill try a try catch and putting a breakpoint in the catch maybe

lean sail
rugged storm
rugged storm
lean sail
#

that might indicate u have a lot of things on 1 line, if an error could not indicate to u what variable was causing the issue

#

honestly ive never used conditional breakpoints before, just remembered hearing about it after i said try catch

fathom plank
#

So I've got this mesh being generated and rendered 100% on the gpu (sorry for the low res vid) As you can kinda see, the mesh surface normals aren't smooth since its generated with marching cubes by appending triangles to a AppendStructuredBuffer. I'm wondering if anyone knows a good way to detect other vertices that are close by to average the normals with to result in a visually smoother mesh. I'm looking for ideas that can be done without having to transfer the mesh back to the cpu, I want to do this as a pass in a shader. https://i.imgur.com/ZDjXyou.mp4

steady moat
fathom plank
steady moat
fathom plank
#

im talking where the mesh is generated

steady moat
#

And, why can you not make the process in the ComputeShader ?

fathom plank
#

it would be

steady moat
#

Just do an average of the normal of each vertex (That are at the same place)

fathom plank
#

like this is how i calculate the normals currently for the whole triangle, but if instead

#

i did something like this, it would be more localized i think

steady moat
#

You will need to explain your image.

#

What are the red line ?

fathom plank
#

red lines would represet the offset where i sample the noise function

steady moat
#

And what would it achieve ?

#

Because the normal would be the same.

#

Only shorter.

fathom plank
#

it shouldnt be i dont think

steady moat
#

Given that you sample the same vector.

#

The normal is normally the cross product of 2 vector composing the triangle.

fathom plank
#

its hard to explain but basically i create the mesh by sampling a noise field, and if i sample closer to the vertex, the noise function should produce more localized results

steady moat
#

(For flat shading)

#

From the look of it, you have the same normal from all your vertices.

fathom plank
#

currently yes, cus im using the corners of the triangle to calculate the normal

steady moat
#

Which result in a flat shading.

fathom plank
#

correct

#

however if instead of using the corners i use closer points, i think it will produce normals that are closer to the average between the triangles

steady moat
#

If you think that you can somehow extrapolate normal from the noise you use to generate your meshes, then do so. However, from my understanding of Marching Cube, the normal are already defined from the subset of meshes you use.

#

If my understand is correct, I might be confusing some concept there, you have a subset of a given size of possible meshes which you predefined. Then from the neighbor of your currently processed "cube", you choose the correct mesh.

fathom plank
#

like if the noise field ground truth is the red line, and the black line is an edge of a triangle, and the current normal is calculated via the triangle corners, it produces the green normals, but if i sample close by the vertices, it should prodice the blue normals im pretty sure

dawn dome
#

Hiya, this is a bit of a weird question, but I'm trying to find a way to take a total value and compare it to some kind of array of addition tables to work out which values it is made up of. There are 4 specific values being compared, the total value can be made up of anywhere between 1 and 6 of these being picked, and no matter which combination there are no duplicate total values by which I mean there can only be 1 answer.

Example:
Input Total Value: 19.23
Values to compare: 4.08, 4.66, 5.25, 5.83
Result: 4.08 + 4.66 + 4.66 + 5.83 = 19.23

Does anyone have any idea how I'd do this?

steady moat
#

Is it the wanted result ?

fathom plank
#

sounds almost like a homework question, but id prob start with the largest value in the set and subtract that from the total, then keep using the largest until its too big for the final amount and move down until its small enough, repeat this, and if no solution, backtrack and try smaller 1 step up, and repeat (basically a generic backtracking algorithm, similar to what can be used to solve sudoku)

dawn dome
steady moat
fathom plank
lean sail
#

u definitely can, but this seems like a problem that doesnt need to exist in the first place

fathom plank
#

(you could also brute force it but that would be very slow in comparison)

steady moat
#

It really depends on what the problem actually is.

fathom plank
lean sail
#

this does look like a school assignment or leetcode question yea lol

steady moat
#

It could be: generate a subset of the given number where it adds up to the given number.

#

Which is widly different than what you are inferring the problem to be.

dawn dome
#

but i'm not sure if there's a more efficient way than the code version of what is effectively trying to figure out someone's pin xD

fathom plank
#

you could also likely solve it with a genetic algorithm

lean sail
#

tbh even running this as combinations (aka brute force) shouldnt be long

steady moat
#

Give a Number X
S <= Randomly sample a number between 0 and the X
Repeat for 0-S and S-X till you get the amount of number you want

#

Recursively.

#

That is given that the problem is what I understand it to be.

fathom plank
steady moat
dawn dome
#

It does seem like a homework question, for a bit more info on what I'm trying to do, is i want to make a little program for tracking how "good" items in a game are, the items can roll stats and each stat roll will be 1 of 4 values which vary based on which stat is rolled, i want to be able to assess the quality of the rolls and therefore the quality of the item overall, here's an example of the stats, this item has 8 values rolled between these 4 stats.

steady moat
#

4.08+4.08+4.08+4.08+4.08=16,32
19.23-16.32=2,91
2.91/4=0.7275
4,8075 + 4,8075 + 4,8075 + 4,8075

steady moat
#

Is it Genshin Impact ?

fathom plank
dawn dome
#

yeah ^ ^

buoyant crane
rugged spear
#

is there a preprocessor define for when you build your project as a "Development Build"?

steady moat
#

Things like those site are made for such things

dawn dome
#

but i'm asking here because I want to make something for it, rather than use the websites which don't do it how i want lol

steady moat
#

What you are doing is known as TheoryCrafting

buoyant crane
rugged spear
#

whoops, found it DEVELOPMENT_BUILD sorry!

buoyant crane
#

oh wait wrong @

steady moat
fathom plank
steady moat
#

Those site has usually made the required work to "guess" the equation.

dawn dome
dawn dome
fathom plank
# dawn dome because you can only know the max value if you know the number of times that sta...

sure, but if you normalize the final roll against the max roll you can determine how close to max it is. Then just add up the normalized stats and the closer to 1 it is, the closer to a perfect roll it is, but you'd likely also want to weight each stat individually based on the type of stat, like flat attack would be much less "valuable" then attack %, etc, so apply weighting to the normalized values, and bam

dawn dome
steady moat
#

Things like health was not contributing to DPS, thus making it irrelevant.

#

Anyway, this is not a Unity question nor a code question.

#

If you want more help, you should consult appropriate resources.

dawn dome
# steady moat I've not play Genshin Impact a lot, however, from what I remember you did not ca...

The type is much more important, but that is mostly why I want to figure out what values the total value is made up of, so I can find out how many times Attack or Crit damage were rolled by simply typing it into a field. Finding out the quality of the roll is secondary to what I'm trying to make, but since as far as I can tell having that information is mandatory, I figured it wouldn't hurt to also know whether I rolled 3 worst rolls, 3 best rolls etc

#

It's not a unity question or a code question when I'm working out how to code it in unity? ๐Ÿค”

fathom plank
#

I guess you could argue since genshin was made with unity, its a unity question ๐Ÿคก

dawn dome
#

I didn't even know genshin was made in unity xD

steady moat
#

Find a good source and make a spreedsheet.

fathom plank
dawn dome
steady moat
wooden knot
#
        if (velocity.x < 0)
            {
                velocity.x += decelerationSpeed * Time.deltaTime;
                if (velocity.x > 0)
                    velocity.x = 0;
            }
            else if (velocity.x < topSpeed)
            {
                velocity.x += accelerationSpeed * Time.deltaTime;
                if (velocity.x > topSpeed)
                    velocity.x = topSpeed;
            }
        transform.position = new Vector2(transform.position.x + (velocity.x * Time.deltaTime), transform.position.y + (velocity.y * Time.deltaTime));```

Am I multiplying by Time.deltaTime too many times?
steady moat
lean sail
#

accelerationSpeed would need to be massive

wooden knot
#

Ok, so I need to take the Time.deltaTime out of the line?
velocity.x += decelerationSpeed * Time.deltaTime;

steady moat
steady moat
tiny mantle
#

I have a major problem

steady moat
#

Also, you will not be able to use real values such as 9.81u/s^2 (Which usually not appropriate in games though)

tiny mantle
#

https://gdl.space/zuzokabuna.cs
I need this code to procedurally generate 50 tiles infront of the player, and destroy 50 tiles behind, it doesn't do that, it just generates 50 tiles

dawn dome
#

I guess all I can do is follow @buoyant crane's advice on looking into "three sum" and "two sum" problems, since it seems they knew how to do what I was looking for

steady moat
#

Or use Pooling

tiny mantle
#

it is procedural generation with random gaps between every tile

#

also waht is Pooling

fathom plank
#

Object pooling is the concept of creating the object then instead of destroying it when its no longer needed, you store its reference and reuse it later

steady moat
fathom plank
#

unity now has built in object pool classs to help with pooling

tiny mantle
wooden knot
steady moat
fathom plank
# tiny mantle so it won't generate and destroy, it will just move them

correct, when you request an object from the pool when there is none allocated, it creates one, but then when you no longer need it you return it to the pool, and instead of getting garbage collected, it sits waiting for you to request another object from the pool, and then its recycled basically

steady moat
merry shore
fathom plank
rugged spear
wooden knot
# steady moat You never explained what the issue is...

I want the character to move frame independent. I also want to do those checks before I apply the acceleration. How can I do both those things and while using Delta Time?

for example
velocity.x += decelerationSpeed * Time.deltaTime;
0 += 1 * .5

transform.position = new Vector2(transform.position.x + (velocity.x * Time.deltaTime), transform.position.y + (velocity.y * Time.deltaTime));
0 + (.5 * .5)

fathom plank
steady moat
fervent furnace
#

pool is just a stack (stack implementation is faster than queue)
pop a object when you need it, else push into stack

fathom plank
rugged spear
#

I wouldn't think of a pool as a queue, as queues typically enqueue/dequeue elements and destroy them. Pools can reuse any element whenever possible in any order

tiny mantle
fervent furnace
#

pool can be implemented as queue dequeue when you need it
but reallocation of queue is not as simple as stack

fathom plank
#

i mean the data structure that holds the items in the "pool" is kinda irrelivant to the usage, you technically "could" use a stack or a list or a queue or a dict or w/e other storage container you wanted for the pool, it effectively just needs to store a reference to the items that are available to keep them from being GC'd

#

granted some structures will be better optimized, but functionall they would all work

lean sail
fervent furnace
fathom plank
#

why not just use a list rather than an array... ๐Ÿ˜

fervent furnace
#

what is list? linked list?

fathom plank
#

no, System.List

fervent furnace
#

list is array

rugged spear
#

list will dynamically resize as needed

wide terrace
#

(The screenshots are of C#'s internal implementation)

fervent furnace
#

it is just an array with some magic (realloction)

fathom plank
#

sure, but like i guess i dont get why it really matters, just set some upper bound on the initial size then u dont need to worry about it moving around in memory as it resizes

steady moat
# fervent furnace

The amount of memory being allocated would result in the same wouldnt ? I guess it would be a bit less ineffective in the copy, however it should not even be measurable.

rugged spear
#

if op doesn't know what you suggested before, i think using a list is the safest bet. especially since reference types are simply the c# version of pointers (4/8 bytes per reference) the list allocation size will be negligible

fathom plank
#

just use unity's built in pool, it has support for a default max size where it reserves the mem for that size, then any requests past that can be handled with normal GC, but ideally u set the max size to be large enough that it doesn't have to switch to non-pooled items

#

so like if u think 50 is the max, set that, then if it accidently happens to go a bit above 50 for a while, it just GC's the extras and only recycles the max of 50.

fervent furnace
#

the memory allocated is the same, but the time of copying is not the same (pipeline, cache miss, etc)
though i dont suggest a newbie to object pool consider those optimizations unless the allocator affect the overall performance (i have written a poor allocator and suffered from it.....

steady moat
fathom plank
#

Ye prob not worth using unless you actually see a measurable performance hit caused by allocations since in most situations the slow downs are a result of other suboptimal code. That said I use pooling literally every day at work (in game dev) and if used correctly, they can make a substantial difference in large projects.

latent latch
#

queue crew represent

sage cliff
#

I am getting this error
Assets/Scripts/TurretAuthoring.cs(17,26): error CS0246: The type or namespace name 'Baker<>' could not be found (are you missing a using directive or an assembly reference?)

With this code:

using UnityEngine;

using Unity.Entities;

public struct Turret : IComponentData
{
    public float shootSpeed;
    public Bullet bulletPrefab;
}

public class TurretAuthoring : MonoBehaviour
{
    public float shootSpeed;
}

public class TurretBaker:Baker<TurretAuthoring>{

}```
I do have the entities in my assembly reference, am I missing any other?
sage cliff
#

Found it, it needs to have Unity.Entities.Hybrid

rugged storm
#

Performance question

Is there any performance difference between using and iterating though a 2d array[Height,Width] vs a normal array[height*Width]?

#

I e been using a normal array for a grid system I've been doing but it's just ended up making things more confusing for alot of the time but I also know I iterate through it and use it alot so I Wana know if there would be any real risk of performance tradeoffs

fathom plank
lean sail
rugged storm
#

Yeah. I was actually only using it because the tutorial/thing I was porting to C# (originally in C++) used it

fathom plank
#

imo store it in a way that makes sense for your use case, if it is a problem that lends itself well to a grid, use a grid

deep oyster
#

Hey all. So I've got a problem. When I pick up an item I want to get the script attached to the item that is of base abstract class BaseItem. However, I also want to destroy the object, so I can't just take a pointer to the script. I need a way to get a new instance of that particular subclass, except I don't know what that subclass IS.

rugged storm
#

Ty, Just wanted make sure before I go through the precess of changing all my methods to work with a 2d array instead of an index just for it to kill the frame rate

fathom plank
rugged storm
#

It's like at say absolutely Max iterating through say 10 of these arrays which are 64 by 64 each

fathom plank
#

yeah u wont see any perf issues at that size

lean sail
rugged storm
#

๐Ÿ‘Œ

latent latch
#

Dont think Unity serializes 2D arrays, but that's not hard to get around

rugged storm
#

Yeah but I don't need to directly set them at all..via the inspectors I mean

#

Also for rendering for making the pixels for an texture are you allowed to pass in a 2d array into that or does it have to be a normal array?

mossy snow
deep oyster
#

Then what is my option, take the whole game object? And what, de-activate it in the heirarchy?

mossy snow
#

no, typically you hide the actual implementation between an abstraction (polymorphic base class or an interface). If you care what the actual type of BaseItem is, your abstraction there is faulty

deep oyster
#

also what is a zombie script bc that doesn't fit my definition of the term

deep oyster
#

I don't WANT to care what the actual type is

latent latch
#

if you don't care for the exact type, perhaps interfaces are what you need

#

oh

mossy snow
#

you set gamestate.curHeldITem to a component on a GameObject, and then destroy that GO. Now the current held item is actually dead, but you're holding a reference to it. Any call that goes to the unmanaged layer (.transform, .name, etc) will throw an exception

deep oyster
#

I just want to get a copy of the BaseItem component so I can call Use after I destroy the object

deep oyster
latent latch
#

Yeah, interface with a use implementation

deep oyster
#

How will that help me

latent latch
#

you make it virtual

deep oyster
#

I still need to get a copy of the script and that copy has to be the sub type

#

so it can call the right Use

mossy snow
#

I don't understand your problem then, if BaseItem has a polymorphic Use method, you can just call it

deep oyster
#

No, I can't, because I've destroyed the object it's attached to

mossy snow
#

it's not destroyed until the end of the frame

deep oyster
#

I want to pick up the item, store it, then later call Use()

#

This is the pick up code

mossy snow
#

then why are you killing it? remove the destroy call

deep oyster
#

Ok so now the item sits on the ground

#

after I walk over it and hit pick up

#

Do I say SetActive(false) and just leave it sort of floating there in the ether

latent latch
#

Why can't you do this all in one frame?

deep oyster
#

I don't want to use the item as soon as I pick it up

latent latch
#

Ah, well, then yeah you have to store it somewhere then

deep oyster
#

I want to

Walk over the item
The item object goes away but I get some info from it and store it
Later the player presses the use item button and calls the appropriate overridden function

latent latch
#

Character needs some inventory holding script then

deep oyster
#

Maybe I can take the prefab and then later get the Use function from the prefab's version of the script?

mossy snow
#

maybe curHeldItem should be a wrapper class around a command that BaseItem generates, that's what my solution would be

fathom plank
#

really depends on the scope of what "use" would do, like do you need it to be visually displayed again, is it going to be in the characters hand, or is it like a consumable, that you can use a generic animation for like drinking a potion, etc

deep oyster
#

The items are really simple, like, potion, fireball scroll, and you can only carry one at a time

#

so I don't really care about having that specific item

fathom plank
#

if its an equipable item like a gun or something, you could just have one of every gun instance already a child of the character, placed in its hand, and just disable all the ones that aren't currently in use, give them an id or something, then when you "pick up" a gun, add that id to the list of available ones that you can swap to. or if using an item is just applying an effect, you could store a dictionary of actions that could be invoked when you "use" an item, and you could keep a count for how many you have, like for example class Consumable { int count; Action OnUse; public Use() { if (count > 0) { OnUse?.Invoke(); count--;}} } then do something like Dict<int,Consumable> and setup all the possible consumables in a player script and update the count of the consumable if the id matches the pickup. or something along those lines

#

could use strings as ids instead like inventory["lesser_health_potion"] or enums inventory[ConsumableType.LesserHealthPotion] = new Consumable(() => health += 10);, etc

#

then when you pick up an item on the ground, call a func like void AddInventoryItem(ConsumableType itemType) { inventory[itemType].count++; } and when you want to use it UseInventoryItem(ConsumableType itemType) { inventory[itemType].Use(); }

#

you could ofcourse build that out into a whole inventory class and pass in the current gameobject as a parameter into the use functions etc, but that would be a pretty simple way of picking something up that can do various things and having it be "usable"

#

if you wanted to shoot a fireball, you could add a "Target" parameter to use, and then do something like UseInventoryItem(Consumable.FireballScroll, enemyTarget); and that could be setup something like inventory[onsumable.FireballScroll] = new Consumable((target) => { /*spawn fireball prefab with "move to target" script*/ });

tawdry jasper
#

My imported character is in a weird scale, defaults to scale 100 imported in unity. In my starterasset 3rd person controller I set my models scale to 50, but in play mode it gets scaled back to 100. (I can "fix" this by leaving it at 100, and scaling the whole playerarmature by 0.5 but this messes with the character controller settings, and I'd rather just scale the model skeleton. searched the few scripts I'm using for "scale" and can't figure out what's causing this?

lean sail
tawdry jasper
lean sail
#

I have no clue. You'll want to ask the people who actually know this stuff, not in the code channel

tawdry jasper
#

@lean sail I don't want to mess with the model, I can insert a scaling empty parent in my player armature above the skeleton, but then it seems the animator doesn't pick it up

forest linden
#

https://hastebin.com/share/cibifosaho.csharp

I have a server-side zombie set up and for some reason it isn't moving at all. If i multiply the chracterController.Move it does move but very stuttery and strange.

Im using mirror, same* as unet

snow quarry
#

i was wondering if anyone knows how to enable and disable sprites and buttons from different scenes when colliding with an object in a different scene

copper rose
#

good morning

wise burrow
#

Hopefully a quick question.

I have a web app that uses TypeScript for typings on the front end and on the node API. I'm thinking of making a unity version but I don't want to lose my library of types.

Is there a way to import typescript types into the C# environment of Unity?

mellow sigil
#

The languages are so different that I doubt there's even a semi-automated way to do that

wise burrow
#

I anticipate a lot of the typescript specific things would have to be simplified down to their most approximate relatives, even if it's not already been done, I'm hoping there's a way to import .ts files and interpret them when building or something similar.

Before I go down that rabbit hole I thought I'd ask in case anyone else had a similar situation.

uneven monolith
#

Idk about the topic but did you try googling already? 'import typescript to c#' seems to find many articles that seem fine if i understood your problem correctly(?). Might be good start to look at those

leaden cipher
gray mural
#

does collision even happen?

mellow sigil
#

Try writing "OnCollisionEnter2D" correctly

gray mural
mellow sigil
#

if that doesn't help, put debug messages outside the if block

leaden cipher
#

Ill try comparetag

#

Ill switch the projectile colliders to triggers

uneven monolith
#

U sure all objects have necessery colliders with right sizes

leaden cipher
#

yeah

uneven monolith
#

And atleast other object must have rigidbody2d

leaden cipher
leaden cipher
#

I am aware

#

woo! it works now!

#

the player character can now fucking die, thanks uwu

uneven monolith
#

Wooo

limber agate
#

๐Ÿ’€

uneven monolith
#

OwO

leaden cipher
mossy shard
limber agate
leaden cipher
#

wha?

limber agate
leaden cipher
#

Im confused lmfao

swift falcon
#

Anime talk in programming channel, crazy

night sparrow
#

is there any way to undo all Physics.IgnoreCollision calls?

#

i want to make bullet instancing and i don't want to associate bullets with certain colliders/objects/factions. I don't want them to keep ignoring the old colliders after they get fired again

woven island
limber agate
sleek bough
#

@limber agate Keep it on topic, please

leaden cipher
limber agate
mental geyser
#

Hellu hellu I created a new project and added a map from the unity asset store (dunno if that's related to the problem), anyways somehow my gravity settings are reversed so +9.81 is falling and -9.81 is somehow floating up in the air pls help sad

leaden cipher
#

would using rb.velocity instead of rb.AddForce prevent my character from sliding?

leaden cipher
#

darn.

night sparrow
#

it just prevents accelerations

#

if you're talking about slopes, you should disable unity's gravity and calculate it for yourself

leaden cipher
#

velocity prevents that?

night sparrow
#

and yes, sliding around is in part, acceleration, so if you use rb.velocity you will prevent sliding around. since you don't accelerate and suddenly happen to stop

swift falcon
night sparrow
#

want to add that alot of games actually use rb.velocity instead of rb.addforce

leaden cipher
#

my current movement code is this but this results in, I guess some weird movements? I think I wrote somethning wrong-

sleek bough
#

There are ways to make wall colliders exempt. You need to check for corner cases and change behavior.

sleek bough
swift falcon
#

AddForce is good for realistic controllers but also requires some more code in order for it to properly work

With AddForce you gain velocity, meaning you will keep it when you stop giving input and thats good for when youre in the air for example. But in order to keep the player from sliding youll need to do some sort of speed control like this

        Vector3 flatVelocity = new Vector3(rb.velocity.x, 0, rb.velocity.z);

        if(flatVelocity.magnitude > moveSpeed)
        {
            Vector3 limitedVelocity = flatVelocity.normalized * moveSpeed;
            rb.velocity = new Vector3(limitedVelocity.x, rb.velocity.y, limitedVelocity.z);
        }
swift falcon
leaden cipher
#

Okay um- tryint to understand that code now--

swift falcon
sleek bough
leaden cipher
#

moveHorizontal = Input.GetAxisRaw("Horizontal");

night sparrow
#

if moveHorizontal is 0, you don't change the velocity, so you'll keep moving

swift falcon
# leaden cipher Okay um- tryint to understand that code now--
  1. Get the players current velocity (flatVelocity)
  2. Check if the magnitude of the player is above the move speed (my input is Input.GetAxis(". . .") * speed * speedMultiplier)
  3. If it is, set it back to normalized flatVelocity (I dont remember how that part works lol)

But basically just making the speed not go overboard

You dont need to do this for Velocity movement, this is for AddForce

swift falcon
leaden cipher
night sparrow
leaden cipher
#

Yeah, Im using 2D

swift falcon
#

Yeah just replace all Vector3's with Vector2's (if youre ever gonna use it at all)

swift falcon
leaden cipher
#

But its a vector 2 value so I do kinda need that 0

night sparrow
# leaden cipher ?

i can smell this will cause you some problems in the future (especially when you try to add falling)

try:

rb.velocity = new Vector2(moveHorizontal * moveSpeed, rb.velocity.y);
leaden cipher
#

Yeah falling got all messed up

swift falcon
leaden cipher
swift falcon
mossy shard
swift falcon
#

I was just talking about more complex controllers

swift falcon
mossy shard
#

because i can work for the character to move by force and i can change the velo based on whatever i want

leaden cipher
#

Okayy, theres no more sliding now!

#

Hm.. Idk if it feels too snappy rn. Eh, I dont have problems with it atm.

leaden cipher
night sparrow
leaden cipher
#

GetAxisRaw

#

I am aware that Raw makes is more snappy.

night sparrow
leaden cipher
#

It does

swift falcon
# leaden cipher Okayy, theres no more sliding now!

Now add a physics material to it with 0 friction, this is so it doesnt stick to walls, is still wont slide though, theres different ways to make it not stick as FogSight said but for this a physics material is good

leaden cipher
#

:>

swift falcon
#

oh alright good

leaden cipher
#

Thanks y'all ^^

mossy shard
#

thanks*

#

oh u corrected mb

swift falcon
#

I made this 2D Rigidbody AddForce based controller a while ago, you can try it if you want, but I dont know the best values

#

Wait

leaden cipher
#

this is my current movement code, horizontal movement and jumping

upper pilot
#

How do I make a grid layout that only expands downwards?
Currently if I force 4 elements in a column and add 5th element it will push the previous 4 elements up.

#

ah

#

Child alignment upper left fixed it -,-

gray mural
#

This method seems to make infinite spawning after changing _textComponent 2nd or 3th time

private void Update()
{
    if (_textComponent.textInfo.lineCount > _textComponentLineCount)
    {
        int firstCharacterIndex = _textComponent.textInfo.lineInfo[^1].firstCharacterIndex;

        string lastLine = text[firstCharacterIndex..];

        text = text[0..firstCharacterIndex];

        textComponentIndex += 1;

        //_textComponents[textComponentIndex].text = lastLine;

        text = lastLine;

        print($"; lastLine: {lastLine}");
    }
}
#
private int textComponentIndex
{
    get => m_textComponentIndex;
    set
    {
        if (value < 0) return;

        while (_textComponents.Count <= value)
        {
            TMP_Text newTextComponent = Instantiate(textComponentPrefab, textComponentsHolder.transform);
            _textComponents.Add(newTextComponent);
        }

        m_textComponentIndex = value;
        _textComponent = _textComponents[value];

        _caretPosition = (text == "\u200B") ? 0 : text.Length;
        AlignCaret();
    }
}
#

Is _textComponent just not set quick enough?

#

everything works if I delete this line:

text = lastLine;
#

also it enters infinite spawning when firstCharacterIndex stats being 0

gray mural
#

they both should be 4, shouldn't they ?

cold egret
#

- I have a list of objects that serve as wrappers on top of strings, and array of strings to insert into the list. Is there a linq query or whatever way to do this other than manually iterating?

ashen yoke
#

ForEach?

#

you can extract the strings into new collection with Select i think

#

then ToArray

night sparrow
#

anyone knows why vs-code hates this snippet?

foreach (MonoBehaviour script in child.gameObject.GetComponents<MonoBehaviour>())
{
    if (!(script is SpriteRenderer))
    {
        script.enabled = false;
    }
}
night sparrow
knotty sun
#

look at the inheritance chain

night sparrow
#

ay, you're correct

rain minnow
#

i should've let them research, my bad . . .

#

easy check . . .

knotty sun
#

they should have checked the docs first

limpid siren
#

Hello.
Guys i have been trying to handle this bug in prints.

So the character is not fixing to the character controller, and i have tried to deactivate everything for testing purposes and that still happening

rain minnow
rotund creek
#

Revisiting a project, this seems to be way out of my depth and it won't let me run the game? Any help would really be appreciated, no idea why this has happened

simple egret
rotund creek
#

Thankyou so much you're a life saver!

rugged storm
#

yo how do you Compare two vector2 ints when sorting a list of them?

#

movementQueue.Sort((a, b) => a.endPosition.<idk what goes here> (b.endPosition));

#

before they were 2 ints and i was just using CompareTo

#

is there no eqivalant for vector2Int?

rain minnow
#

you'd compare the x value of both or the y value if the x are equal: a.x.CompareTo(b.x) . . .

rugged storm
#

ah, actually never mind due to some changes i made to the code i dont actually need to sort this lol

ashen yoke
#

what type is a ?

rain minnow
#

it prolly (should) has a default implementation . . .

tardy tendon
#

Guys, I have a prefab for my pause screen and options screen. The script that controls the Pause UI is attached to the main Canvas game object. Everything works fine, but when I change scene and Instantiate the Pause UI prefab, it creates two. When the 3rd scene loads it then creates 3. It's like the Pause UI script isn't getting destroyed on load, even though I'm not uses Don't Destroy On Load... anyone come across something like this before?

rain minnow
tardy tendon
#

I'm creating a tool. I want someone else to design the UI in a prefab.

rotund creek
ashen yoke
uneven monolith
#

Im not sure what kind of problem u mean. Do you want to stack those rotations or ignore another. Anyways the usual solve to problems like this ive done, is to make player object not have sprite renderer, and just have the code stuff, and have yhe player object have child with spriterendereers and animations

tardy tendon
uneven monolith
tardy tendon
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.

simple egret
rotund creek
#

okay thankyou

uneven monolith
#

Yeah

#

And animation and sprite renderer should be same object

tardy tendon
#
        private void Pause()
        {
            if (isPaused)
            {
                ClosePauseUI();
            }
            else
            {
                if (PauseGO == null)
                {
                    if (OverlayGO == null)
                        OverlayGO = GameObject.FindWithTag("UI-ROOT");
                    
                    PauseGO = Instantiate(UIUtilities.GetPauseUI(), Vector3.zero, Quaternion.identity);
                    PauseGO.name = "PauseUI";
                    PauseGO.transform.SetParent(OverlayGO.transform, false);
                }

                ClearButtons();


                isPaused = true;
                canSelect = true;
                Time.timeScale = 0;
            }
        }
ashen yoke
tardy tendon
ashen yoke
#

where do you call Pause from

#

most likely several calls happen

tardy tendon
#

OOOOOOOOOOOOhhhhhhhhhhhhhh

#

That might be it

#

Sorry guys, I'm a dummy. Pause is called from an event thats fired in the input manager. I've been making changes to the input system and I edited out the line where I unsubscribe from the event. Let me try that.

#

Yep, that was it. I'm an idiot...

#

Thank you @ashen yoke

knotty sun
ashen yoke
#

wrestling with poor KCC architecture here

#

the whole thing is controlled by KinematicCharacterSystem

#

KCCMotors register in it

#

but no collisions are detected if the KinematicCharacterSystem is not in the same scene as the motors

#

when i drag it to the scene with motors at runtime they start working

#

actually no it deletes itself

#

anyone has clues as to why overlap methods can fail in multi scene scenario?

somber nacelle
#

pretty sure each scene is a separate physics scene

ashen yoke
#

but Physics api is static

somber nacelle
warm stratus
#

hey, can i optimize that code?

private string EncryptDecryptData(string _dataToEncrypt)
    {
        string result = "";

        for (int i = 0; i < _dataToEncrypt.Length; i++)
        {
            result += (char)(_dataToEncrypt[i] ^ encryptionKey[i % encryptionKey.Length]);
        }
        
        return result;
    }

mossy snow
#

that is O(n^2), use a string builder and reserve _dataToEncrypt's length. Probably can't do better than that unles you want to do unnecessary multithreading stuff

ashen yoke
warm stratus
ashen yoke
#

if you really want to optimize it look into ZString

mossy snow
#

yes, and since you already know how many chars will be in there, init SB's capacity

warm stratus
mossy snow
#

StringBuilder result = new StringBuilder(_dataToEncrypt.Length);

warm stratus
mossy snow
#

it will avoid some unnecessary copying, so yes by probably a negligible amount overall unless you're cramming tens of megabytes+ through this encryption method

rugged storm
#
    public void GenerateChunk(Vector2Int chunkLocation)
    {
        MapChunk chunk = GetChunkDirect(chunkLocation);
        int sbaseHeight = 20;
        int sheightMod = 15;

        int gbaseHeight = 15;
        int gheightMod = 4;

        int waterHeight = 25;
        float scale = GameLogic.i.pnScale;

        int[] surfaceHeightOffsets = GetHightOffsets(sbaseHeight, sheightMod, scale, chunkLocation.x, chunkLocation.y);
        int[] stoneHeightOffsets = GetHightOffsets(gbaseHeight, gheightMod, scale, chunkLocation.x, chunkLocation.y);
        for (int x = 0; x < MapChunk.chunkSize; x++)
        {
            for (int y = 0; y < MapChunk.chunkSize; y++)
            {
                int surfaceHeight = surfaceHeightOffsets[x];
                int stoneHeight = stoneHeightOffsets[x];
                if (y <= surfaceHeight) { chunk.SetCell(x, y, new Sand()); }
                if (y <= stoneHeight && y <= surfaceHeight) { chunk.SetCell(x, y, new Stone()); }
                if (y <= waterHeight && chunk.GetCell(x, y) == null) { chunk.SetCell(x, y, new Water()); }
            }
        }
    }
    public int[] GetHightOffsets(int baseHieght, int maxMod, float scale, int chunkX, int chunkY)
    {
        int[] Offsets = new int[MapChunk.chunkSize];

        for (int x = 0; x < MapChunk.chunkSize; x++)
        {
            float xcord = (float)x / MapChunk.chunkSize * scale + xNoiseOffset + chunkX;
            Offsets[x] = Mathf.RoundToInt(baseHieght + (maxMod * Mathf.PerlinNoise(xcord, yNoiseOffset + chunkY)));
        }

        return Offsets;
    }```
y and x NoiseOffset are set to a random number on start so why is result always the same?
#

wait nm i think i was accidentally calling this before i actually set them

crimson atlas
#

this is supposed to "search" for this pair of components (input and centipede)
problem is i don't know if this "tool" is going to be a child of the centipede (which has the input and the centipede components)
or a child of a child
is there some function that will search all parents (until there is no parent) for a component?

somber nacelle
#

GetComponentInParent is a thing

crimson atlas
crimson atlas
somber nacelle
#

it does search the object you call it on first then goes up the chain of parents until it finds the component

crimson atlas
#

dude i really need to set some time apart to just read all the functions

#

so often i feel like i'm reinventing the wheel

#

a way worse wheel too

knotty sun
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
#

read the last line

rain minnow
#

this is general for crying out load . . .

ashen yoke
#

mesh collider zero bounds in editor, convex has proper bounds, concave zero

#

whats up with that

#

Physics.SyncTransforms();
called before ops

#

seems like the mesh has holes

rain minnow
# gray mural Actully I should ask why is `TMP_Text.textInfo.lineCount == 4` and `TMP_textInfo...

TMP_Text.textInfo.lineCount is the number of visible lines based on the size of the text container and the content. if your content is bigger than the container, it will continue the text on a separate line and add to line count (even if the original text does not use a new line character)

TMP_textInfo.lineInfo is an array that holds information about each line. its Length is increased in memory to ensure capacity. it will double its length when the lineCount value is greater than its current length. at any point in time, does your lineCount surpass 4?

dawn dome
swift falcon
#

how do I make this ball not be stuck and just automatically pop away from the tilemap edges?

gray mural
#

probably it shouldn't

#

but I think it does not, I have checked it

#

it's just 4

#

though I wonder if my issue is caused, because _textComponent cannot be changed quick enough in Update()

#

that's why I am now going to make a coroutine that doesn't allow to type in custom Input Field when changing the line too

rain minnow
gray mural
#

lineCount does never exceed lineInfo.Length

#

I am a lil bit confused

rain minnow
gray mural
gray mural
#

you have mentioned it, haven't you?

limber granite
#

Anyone know why orbiting it vertically breaks it? I am using an empty gameobject at the position of the sun and rotating it while the planet is the child of that said gameobject. This script is attached to the empty gameobject:

rain minnow
limber granite
sleek heath
heady iris
#

i brought this up last time they asked about this, lol

sleek heath
#

:P

#

its better and safer encryption ยฏ_(ใƒ„)_/ยฏ

lean sail
#

Doesnt even have to be AES, just using anything other than self made encryption

gray mural
sleek heath
#

seems a bit beginner to me

gray mural
#

cause I now get this

limber granite
rain minnow
gray mural
gray mural
rain minnow
lean sail
#

U realize your scripts (a component) can GetComponent right?

sleek heath
#

yeah

gray mural
rain minnow
# gray mural So what can I do if I can't control it? So I check if the `lineCount` does not e...

you can store lineInfo.Length in a variable every time the text is updated and log that along with lineInfo.Length. the easy way is to just log lineCount and lineInfo.Length and see when either value changes. i do this . . .```cs
Debug.Log($"Line Count: <color=cyan>{_textField.textInfo.lineCount}</color>");
Debug.Log($"Line Info Length: <color=cyan>{_textField.textInfo.lineInfo.Length}</color>");

lean sail
gray mural
#

I thought that's just in TMP_Text

rain minnow
gray mural
#

no, I haven't even thought about it.

gray mural
#

everything worked nice unitil 8th _textComponent

#

that's what has happpened

#

it has changed 9 _textComponents at the exactly same time

#

or 8

#

it shoudn't though.

#

I have coroutine.

#

I don't see any reason why it can happen

private string text
{
    get => _textComponent.text;
    set
    {
        StartCoroutine(SetTextHelper());

        IEnumerator SetTextHelper()
        {
            yield return new WaitUntil(() => _setTextCoroutine == null);

            _setTextCoroutine = StartCoroutine(SetText());

            IEnumerator SetText()
            {
                if (value == null)
                    value = string.Empty;

                value = value.Replace("\0", string.Empty).Replace("\u200B", string.Empty);

                _caretPosition = value.Length;

                if (value.Length == 0)
                    value = "\u200B";

                _textComponent.text = value;

                _textComponent.ForceMeshUpdate();

                AlignCaret();

                if (_textComponent.textInfo.lineCount > _textComponentLineCount)
                {
                    int firstCharacterIndex = _textComponent.textInfo.lineInfo[^1].firstCharacterIndex;

                    string lastLine = text[firstCharacterIndex..];

                    text = text[0..firstCharacterIndex];

                    textComponentIndex += 1;

                    text = lastLine;

                    Debug.Log($"Line Count: <color=cyan>{_textComponent.textInfo.lineCount}</color>; Line Info Length: <color=cyan>{_textComponent.textInfo.lineInfo.Length}</color>");
                }

                yield break;
            }
        }
    }
}
hidden veldt
#

Anyone got any ideas on how to debug what is moving my transform? I have one script which is instantiating a gameobject in frame one. At the end of Start in the script that instantiates the object, I print out the position of the instantiated object (first line in img). In Start on a script on the instantiated object, I then print out the position (line 2 in the img), and the position is now different. I have absolutely 0 idea what is moving it. I looked for data breakpoints, but that only works with .net 4 in Rider ๐Ÿ˜ฆ

rain minnow
hidden veldt
#

I tshould be the first thing I print

#

But something is moving them to 0 0 0

rain minnow
#

that's the local position . . .

#

is it a child of a parent object?

hidden veldt
#

No

#

That's really not the problem

icy pebble
#

hmmmm any thoughts on this one:

Severity    Code    Description    Project    File    Line    Suppression State
Warning    CS8032    An instance of analyzer Unity.MonoScriptGenerator.MonoScriptInfoGenerator cannot be created from C:\Program Files\Unity\Hub\Editor\2022.3.2f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.SourceGenerators.dll: Could not load file or assembly 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified..    Assembly-CSharp-firstpass    C:\Program Files\Unity\Hub\Editor\2022.3.2f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.SourceGenerators.dll    1    Active
hidden veldt
#

You see that the first position is being printed correctly

#

But then they're being moved by something

rain minnow
#

how are you getting the positions from code?

hidden veldt
#

Dude it's not a problem of getting the right position

#

I know it's being spawned correctly

#

But something is moving them

rain minnow
#

yeah, but we don't know that. we can't assume anything. we need all the info to help solve the problem . . .

#

your code will obviously help with that . . .

hidden veldt
#

Debug.Log($"Gen {GameObject.Find("Octopus(Clone)").transform.position} frame {Time.frameCount}");

lean sail
#

Just to confirm, is it actually moving visually?
If so, I'd just start by removing scripts from the object to see which is the culprit

earnest gazelle
#

How can I implement fog of war in a voxel game?
Define a boolean field for each voxel named IsVisible and by moving characters (npcs) set them as visible voxels?

rugged storm
#
    public void DrawWorld()
    {
        disptext = new Texture2D(MapChunk.chunkSize, MapChunk.chunkSize);
        Color32[] colors = new Color32[MapChunk.chunkSize * MapChunk.chunkSize];

        for (int x = 0; x < MapChunk.chunkSize; x++)
        {
            for (int y = 0; y < MapChunk.chunkSize; y++)
            {
                int colorpos = x + y * MapChunk.chunkSize;
                colors[colorpos] = BGC;
                Element element = GetCell(x, y);

                if (element != null)
                {
                    colors[colorpos] = element.color;

                    if (element.asleep) { colors[colorpos] -= new Color(.5f, .5f, .5f, 0); }
                }

                if (overlayColors[colorpos] != Color.clear)
                {
                    colors[colorpos] = overlayColors[colorpos];
                }
            }
        }
        Array.Clear(overlayColors, 0, overlayColors.Length);
        disptext.SetPixels32(colors);
        disptext.filterMode = FilterMode.Point;
        disptext.Apply();  // Apply changes to the texture

        // Set the pixels of the texture using the extracted colors
        display.texture = disptext;

    }

this is a script i have for drawing a world but its very laggy any thoughts on possible optimization?

hidden veldt
#

As the screenshot shows, its the same frame. But 2 very different positions on the same object

rain minnow
rugged storm
hidden veldt
# rain minnow do you provide a position when instantiating the GameObject?

Yeah, that is the first and correct position that is logged.

#if UNITY_EDITOR
            GameObject obj;
            if (!Application.isPlaying)
                obj = UnityEditor.PrefabUtility.InstantiatePrefab(prefab, transform) as GameObject;
            else
                obj = Instantiate(prefab, transform);
#else
            var obj = Instantiate(prefab, transform);
#endif
            obj.transform.position = spawnPosition;
earnest gazelle
#

Use job system

#

for each chunk

#

What size does your world have?

hidden veldt
#

As I've said, the first position is correct, so the spawn position is as I want it. But something is moving it inbetween

#

I just want a way to debug what is moving it

#

I already tried disabling all scripts on the object

#

No change

rugged storm
earnest gazelle
#

What size does your world have?

flint needle
#

how do you perform a Ctrl+Z from script?
Like how can i trigger an Undo to take action ๐Ÿง

flint needle
#

the point is binding to gamepad

leaden solstice
#

Are you trying to implement undo

flint needle
#

i have it implemented with keyboard

leaden solstice
#

Or are you trying to implement keybinding

rain minnow
earnest gazelle
flint needle
#

triggering undo without using CtrlZ

earnest gazelle
#

If you use new input system, it will be really straightforward

flint needle
#

i do

leaden solstice
#

Well.. don't rely on ctrl+Z

#

Make it as action

flint needle
#

i tried looking for CtrlZ and its not there (Actions)

#

but how do i call whatever process gets called when you press CtrlZ?

#

because i have the callback that reads the undone data, but if i call it directly nothing is undone (it just re-reads oc)

heady iris
#

i'm unclear on what causes it, though

#

it doesn't seem to stop analysis from happening

icy pebble
#

yeah everything seems to be working

#

just a strange warning

hidden veldt
#

Is red hat getting into Unity? ๐Ÿ‘€

#

jk haha

eager pewter
#

I appear to be getting an error on the StartCoroutine line. Any idea why? (and yes there's a reason I'm making printf a coroutine, I'm not crazy)```cs
public void printf(string text, params object[] formatting)
{
StartCoroutine("_printf", (text, formatting));
}

...

private System.Collections.IEnumerator _printf(string text, params object[] formatting)
{
yield return null;
}```

#

Trying to do it similar to the c printf where you pass in a string + any number of other args (including 0) of various types and it uses the format specifiers to put them in the correct places

leaden solstice
#

Don't use string based one

leaden solstice
heady iris
#

yes, just invoke the method and pass the result to StartCoroutine

#

you might be thinking of how you can't just put a method directly into Invoke

#

(which always takes a string)

knotty sun
#

this syntax

StartCoroutine("_printf", (text, formatting));

is not this

public Coroutine StartCoroutine(string methodName, object value = null); 

Not sure how you came by it

leaden solstice
#

Well.. it is

#

Just that second argument is tuple

knotty sun
#

ah, true, didn't spot that

flint needle
eager pewter
knotty sun
#

dont think you can use params in a Coroutine

eager pewter
#

aight, lemme try a few things and I'll get back to you

leaden solstice
#

If that is the error it sounds like you are doing something like new MyMonoBehaviour()

eager pewter
#

I made the class this is in extend MonoBehaviour

#

class TextTerminal:MonoBehaviour

mystic rock
#

does anyone have a script for some procedural generation of low-poly-ish terrain

lunar hornet
#

Does anyone have any code for a farm system such as adding seeds and water and waiting for them to grow

leaden solstice
eager pewter
#

I don't believe this script is attached to a GameObject at all. It's part of a plugin

leaden solstice
#

That's not gonna work. Game object is necessary if you want to run coroutine.

#

You might look into C# Task instead.

#

MonoBehaviour shouldn't be used without GameObject

soft shard
eager pewter
#

I know people've used coroutines in plugins before. Not exactly sure how to plugin loader handles em. It could attach them to a GameObject. Is there any way to check?

#

from a different plugin https://github.com/Permamiss/HFF_SpeedTools/blob/master/HFF_SpeedTools/SpeedTools.cs ```cs
public void DebugMessage(string theText, float amtSeconds = 2.0f, bool logIt = true)
{
if (logIt)
Shell.Print("<#00AA00>SpeedTools></color> " + theText);
else
{
amtSeconds = System.Math.Max(amtSeconds, 1.0f); // any less may cause the game to lag
StopCoroutine("ClearMessage");

            renderDebug = true;
            debugText = theText;

            StartCoroutine("ClearMessage", amtSeconds);
        }
    }

    private System.Collections.IEnumerator ClearMessage(float seconds)
    {
        yield return new WaitForSeconds(seconds);
        renderDebug = false;
    }```
#

^ uses coroutines

mystic rock
#

i didn't ask for code

eager pewter
#

class extends from BaseUnityPlugin which extends from MonoBehaviour

mystic rock
#

oh that

#

i didn't realize i sent it in this channel sorry

lunar hornet
#

I want to know how it works and what is its principle

#

i need to make it like a simpel stardew valley

leaden solstice
#

Probably somewhere in their documentation?

sleek bough
lunar hornet
#

ok thanks for your time

thin hollow
#

Can somebody help me please? My unity editor crashes when the function reaches DestroyImmediate.
The function supposed to create or edit children (A simple mesh plane) of a game object according to an array of structs, and if there's more children than entries in the array, to trim the children.

#if UNITY_EDITOR
        private void OnDrawGizmos()
        {
            //If I check this parameter in the Inspector, editor runs the function once.
            if (DEV_UpdateBkg)
            {
                DEV_UpdateBkg = false;
                PopulateBackground();
            }
        }
#endif
internal void PopulateBackground()
        {
            if (bkgParent.childCount > bkgLayers.Length)
            {
                int excess = bkgParent.childCount - bkgLayers.Length;
                if (excess > 0)
                {
                    DevLog.Log("bgP: "+bkgParent.childCount+"bgL: "+bkgLayers.Length+"excess: "+excess );
                    for (int i = 0; i < excess; i++)
                    {                                                bkgParent.GetChild(excess).gameObject.SetActive(false);                        DestroyImmediate(bkgParent.GetChild(excess).gameObject);
                    }
                }
            }
            foreach (BkgImageElement layer in bkgLayers)
            {
                for (int i = 0; i < bkgLayers.Length; i++)
                {
                    if(bkgParent.childCount > i && bkgParent.childCount !=0)
                        if (bkgParent.GetChild(i))
                        {
                            UpdatePlane(i);
                            continue;
                        }
                    CreatePlane(i);
                }
            }
        }
eager pewter
# leaden solstice Then it sounds like you missed some step that you should follow

Alright update. The main class extends from BaseUnityPlugin. Running the code as a part of that class works beautifully (Hooray!), which is what the code in the GitHub repo does. In my case, I don't want the coroutine to be part of the main plugin class, but instead from different class. That's definitively where the issue lies, not in any of the "optional argument"/params keyword stuff. Imma look at Task and at the plugin documentation some more

limpid siren
#

Guys how can i make a 3d character jump trough a barrier with parkour animation, instead of normal jump?
Like if i press space i jump normaly.
But when the object forward is not tall enough and the character is running i want to jump with another animation i have.
Problem is that i dont know how tall is the part of the object im trying to jump into, in order to add specific velocity.y

thin hollow
leaden solstice
thin hollow
#

That's the new iteration, before that I tried to just delete all children by for-looping through bkgParent.childCount - it crashes as well. This iteration yeah it isn't out of the bounds, if I comment the destroy line it runs bkgParent.GetChild(excess).gameObject.SetActive(false); successfully

eager pewter
leaden solstice
eager pewter
#

got it working

#

it was stupidly simple

#
Main.instance.StartCoroutine(_printf(text, formatting));```where `Main` is my `BaseUnityPlugin`
thin hollow
leaden solstice
thin hollow
#

How would I do that?

rain atlas
#

Im making an android game, I am trying to figure out the best way to do look input, I think personally 2 sticks dont really work in my case so how can I take looking input in a better way than in that of another joystick?

#

wait am min, some games dont have a second stick, the one half of the screen acts like a touch pad, how would one do this?

ashen yoke
#

nevermind i see the idea

#

@thin hollow try this one

#
        public static Transform DestroyAllChildrenImmidiate(this Transform tr, bool onlyActive = false)
        {
            for (int i = tr.childCount - 1; i >= 0; i--)
            {
                var c = tr.GetChild(i).gameObject;
                if (onlyActive)
                {
                    if (c.activeSelf)
                        GameObject.DestroyImmediate(c);
                }
                else
                    GameObject.DestroyImmediate(c);
            }

            return tr;
        }
#

never crashed for me

rain atlas
#

ok, so i am using the new input system, i made 3 raw images, they all have the On-screen button component and are maped to the path that should do their function, the jump button works, but I cant for the life of me get the others to do anything

#

also for testing sake i did do cs if (pause.WasPressedThisFrame()) { print("something"); }
and this still showed nothing

latent latch
#

Start logging the methods after input

rain atlas
#

say i had pause mapped th the path start [gamepad]I had it the same on the component but like I said not even that in update did anything

latent latch
#

When you say on-screen button, are you just assigning a UI button event to a method

#

and if so, check if raycasting is being blocked

rain atlas
#

no with the new input system there is a script or component of sorts that i put on a raw image that said On-Screen Button you put the path you want it to take the place of and it puts in its value there

#

im not using the ui button

latent latch
#

Ah, ok not that familiar with those but seems just like it binds other control devices besides touch/mouse to the event system

rain atlas
#

yes, I have one for jumping, it works just fine, but the other 2 dont

latent latch
#

Other button input doesn't seem to work either with it?

rain atlas
#

there all set up the same, just one works

#

ok, i have no idea now, i changed jumps input to pauses, south to start

latent latch
#

Try changing pause to your jump key

rain atlas
#

and now it worked

#

ima just duplicate jump and remap the duplicates

#

ill let ya know if that works

latent latch
#

could be just not recognizing the input would be my best guess

rain atlas
#

i know what the problem is when ever i do shift alt than do the top right corner to snap the images there it dosent work

#

but they do if there snapped to the side like jump was

#

thats very odd, but hay i did fix the issue

#

thanks for your assistance

#

new discovery, its not the snap position its i think hight

#

or maybe just being in the corner

#

ok... final conclusion...

#

the buttons only work in a select few spots

#

now all I have to do is find those spots and pick the ones that make the most sence for the button to be in

#

ok... last time...

#

it was because the input was on a seperate canvase

#

this is my final conclusion

latent latch
thin hollow
ashen yoke
#
sometransform.DestroyAllChildrenImmidiate();
#

if this crashes this is not the culprit

#

not this method, it can be anything before it, or during it, like some code in OnDestroy/OnDisable in the objects you are destroying

leaden ice
#

waht are these blurry images supposed to show?

#

hjow are we supposd to help with this

#

we don';t even know what the issue is

#

that si so vague as to be meaningless

#

you have only shown about 1/3 of the setup involved in making that work

#

you have to also show your code and how you hooked the code up to the input stuff

cobalt gyro
#

Visual Studio or VS Code

leaden ice
#

no control schemes checked for the XR button

#

put it on all

#

also this is a different action

#

from the "Space" action

#

your action names are quite confusing too - they shouldn't be named after buttons

#

but anyway - you'd again have to show how you hooked this up to your code

#

because for all I know you just didn't hook this up but you hooked up the space one

#

looks like you have an error in your console

#

why not fix it :p

#

juist update or remove that package

#

that would annoy the hell out of me

#

especially if this not really not a code issue

#

you cxan and should also use the input system input debugger

rain atlas
#

so I finally made my game for android, I have one issue though, I want a 16:9 aspect ratio i put it to legacy which i heard is 16:9, but on my phona after the apk was installed i saw the background behind the canvas which i needed in world view for something , how do I make my game only show 16:9 and not whatever my phone decoded to use

leaden ice
eager pewter
#

How would I import a font (using C#) without it being a system-wide installed font? Running cs Font exampleFont = new Font("C:\exact\path\to\font.otf");Doesn't seem to work

eager pewter
#

No, but the Unity docs explictly mention that Unity can work with both ttf and otf files, so I don't see why it would treat them differently in this case

ashen yoke
#

youre testing in build?

eager pewter
#

I'm working on a plugin, which is why I need to load my assets during runtime via scripting. I launch the full game every time I go to test. I am not working through the Unity editor, only Visual Studio

tiny mantle
#

I am doing object pooling, and when I wrote ObjectPool I got this error

The type or namespace name 'ObjectPool' could not be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]
steady moat
eager pewter
wide terrace
tiny mantle
ashen yoke
#

says "name" not path and no mention it creates anything from that path

tiny mantle
#

didn't work

ashen yoke
tiny mantle
#

I think I might see the error

#

yep, forgot to add a type

#

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

tiny mantle
# ashen yoke 2020?

do you know how to fix this?

Cannot implicitly convert type 'GrassPooling' to 'UnityEngine.Pool.ObjectPool<UnityEngine.GameObject>' [Assembly-CSharp]csharp(CS0029)
steady moat
#

You did not implement correctly the singleton pattern.

tiny mantle
steady moat
#

public static ObjectPool<GameObject> instance is of not a GrassPooling.

#

What you tried to do with instance.

tiny mantle
#

what should I do

tiny mantle
steady moat
steady moat
#

This is impossible that you have read and understood completely the page. Otherwise you would not be asking the question.

tiny mantle
steady moat
#

Also, the error you have is trivial. If you want the quick fix is to change the type of the object at line 7 to GrassPooling.

#

However, you should take your time to correctly understand the Singleton Pattern and implement a better variation.

#

Here is my current implementation for Reference:

using UnityEngine;

public abstract class Singleton<T> : MonoBehaviour
    where T : MonoBehaviour
{
    private static T instance = null;

    public static T Instance
    {
        get
        {
            if (instance != null)
                return instance;

            instance = FindObjectOfType<T>();

            if (instance != null)
                return instance;

            GameObject resource = Resources.Load<GameObject>($"Singleton/{typeof(T).Name}");
            instance = Instantiate(resource).GetComponent<T>();
            DontDestroyOnLoad(instance.gameObject);

            return instance;
        }
    }
}
tiny mantle
steady moat
#

Read the page.

#

How far you hope to go if you cannot find simple answer yourself when they are literally setting in front of you.

tiny mantle
#

I prefer having someone with experience explain it in a shorter way, than having to read a 3000 word page, beacuse after all, I code, not read

buoyant crane
#

99% of coding is reading

steady moat
tiny mantle
leaden solstice
#

The people with experience wrote that page.

steady moat
#

Instead, they leave books and post.

#

If you really want to have a typed experience, you can ask an LLM. You might be lucky and find some answer that are valid.

compact spire
#

So, I've been using Unity events and looking at various videos on their application, but one thing confuses me. Most of the examples just directly set the subscriptions for the events in the editor. Managing all the even subscriptions between objects without having directly references doesn't seem to be covered clearly. I guess that just ends up becoming a "how to manage" the game in a way that makes sense without a mishmash of game managers with direct references to each other.

latent latch
#

There's a lot you can just write your own if you wanted to, but UI button events are pretty convenient and I do use a lot of those.

ashen yoke
#

unity events should only be used to hook local things like ui/some events in the same object that dont lead to massive callstacks

compact spire
#

So it's reasonable for major systems to just use direct references instead?

ashen yoke
#

systems should have a way to locate each other using at least some sort of service locator

#

GetComponent<T> is an example of one

#

they can also communicate through event bus

#

or have dependencies injected with the likes of zenject

compact spire
#

haven't looked at an Evant bus, heard the term before

#

Zenject? is that a unity specific DI solution?

leaden ice
#

The opposite

#

It's a generic C# one

ashen yoke
#

its extenject now

compact spire
#

I think the only one I ever looked at was Autofac

#

but that was a cursory glance

ashen yoke
#

extenject is tailored for unity

compact spire
#

service locator typically relies on a singleton doesn't it?

ashen yoke
#

everything relies on singleton in one way or another

#

DI relies on a container

compact spire
#

ahh so avoiding singletons at all costs may not be a good route

ashen yoke
#

minimizing them yes, completely avoiding unreasonable

#

need to have big part of all the game code non static, utilities can be static, editor tools, some cross edtor/runtime tooling, root containers/locators