#archived-code-general

1 messages ยท Page 31 of 1

west sparrow
#

We use TeamCity (Unity cloud is no help as we support a lot of platforms and many engines - not just unity), in most cases I'd say the work isn't usually worth it for automatic testing. But we have PS5, Xbox, VR, AR, web, desktop games and projects. So we need a lot more QA on unity releases than a normal company

peak pivot
#

I am checking if certain methods are not stripped away.

peak pivot
#

Because the project I'm working on uses a library that doesn't directly call these methods. So if stripping is set to high they are removed.

west sparrow
#

We try to not use Unity services for anything though, they accidentally disabled our license keys once and it shut down a major project the day a hospital release was needed. That kind of ended us depending on Unity for anything

hexed oak
#

Yeah I'll likely end up migrating away from jenkins for building stuff, then some kind of VM or docker deployment to actually run the built applications

#

Oh my god, you build hospital software?

polar marten
peak pivot
#

Causing exceptions at runtime. I want to set stripping to high since it removes a lot of memory usage.

west sparrow
polar marten
#

y: "sometimes, some methods are stripped away, and i would like them not to be"

#

is that correct?

#

are you familiar with the [Preserve] attribute?

peak pivot
#

The question I have is. Given a System.Type can I somehow get which line that class is defined?

west sparrow
#

Hense the complex as heck build server and QA requirements ๐Ÿ˜„

polar marten
peak pivot
hexed oak
#

Yeah I've heard of teamcity and the pricing seems pretty high for our needs

west sparrow
#

At a past company we had a great experience with Jenkins though.

peak pivot
#

what I have now generates a list of these types but in type names, rather than file/linenumber

polar marten
#

what you are doing doesn't make sense.

west sparrow
#

Team city does have a pretty good free tier now though

peak pivot
#

It's basically a Lint >_>

#

I feel it make sense

polar marten
#

anyway, no, you cannot get the line number, sorry. it will take you longer to verify this stuff and write the linter than it would be to fix it once

#

your library sounds buggy

hexed oak
#

I'll definitely have to try the free tier on some personal stuff. I like the on prem options when I can get them

polar marten
#

it should call the methods directly

peak pivot
#

Oh yes, I very much don't like it. But it's a 5 year old project and I joined it late.

polar marten
#

you are developing a video game and you're trying to use a sophisticated feature, code stripping. you should spend the time fixing the library

#

well

#

no one is going to use the linter but you

#

so think this one through critically

peak pivot
#

They already have unit tests running

#

The plan is to run it inside a unit test to conform with the current workflow.

polar marten
#

it is a colossal waste of time to write a linter for this. fix the library

peak pivot
polar marten
#

if you can already mechanistically determine which methods you need, you can generate a link.xml instead*

#

it doesn't make sense to author a linter. just generate the link.xml

peak pivot
#

Can I do that for constructors as well?

#

with arbitary arguments?

polar marten
#

why wouldn't you be able to?

#

anyway, you haven't really gotten to the y of your xy problem

pine jungle
#

Assets\Scrips\SelectionManager.cs(9,5): error CS0246: The type or namespace name 'Text' could not be found (are you missing a using directive or an assembly reference?)

polar marten
#

what are you trying to do?

pine jungle
#

those shamone now how to fix this

polar marten
#

what is going on in the game?

leaden ice
pine jungle
#

i have it but the place wear i should but it those not show

potent sleet
swift falcon
#

Is there a way to include the detail meshes into the terrain heightmap? For example, if I paint a bunch of 1x1x1 cubes onto a flat terrain, there should be a bunch of height=0.5f on the heightmap
If there's a way to do this with trees, that would be great as well

peak pivot
# polar marten what are you trying to do?

My base problem is that I need to decrease the memory usage to avoid crashes at runtime on certain platforms.
Through profiling I've located that 90+ MB can be removed by enabling high stripping (this is a lot more than most other areas).
The problem is that the game is using this dependency injection system that creates various objects and feeds them their arguments into their constructors.
These are stripped away and there are a few 100 instances of this.

#

I've written code that identifies the types and I can go through and fix all these. But unless I can get some sort of system in place that detects cases. Any new class added to the game would cause a runtime error on that platform.

leaden ice
peak pivot
#

So my goal is to run some reflection code in a unit test which can find all of these cases. and print out the file/line of that class rather than System.Type.FullName

#

Well a playmode unit test

pine jungle
polar marten
peak pivot
#

But yes, it is il2cpp

hexed oak
#

Is there some optimization that can be done?

#

Are there memory leaks? How large are your memory leaks?

peak pivot
#

There are other optimizations that can be done.

polar marten
#

NDA: "not doing anything"

peak pivot
#

But decreasing the executable+dll size is the low hanging fruit I've located

hexed oak
#

Seems like a lot of work for low hanging fruit

polar marten
#

well good luck on your journey here

peak pivot
#

Thank you.

hexed oak
#

I'd go through every class and check Update loops first

potent sleet
polar marten
#

i'm not sure what platform would be sensitive for a 5 year old game

pine jungle
# potent sleet What donโ€™t you get

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

public class SelectionManager : MonoBehaviour
{

public GameObject interaction_Info_UI;
Text interaction_text;

private void Start()
{
    interaction_text = interaction_Info_UI.GetComponent<Text>();
}

void Update()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit))
    {
        var selectionTransform = hit.transform;

        if (selectionTransform.GetComponent<InteractableObject>())
        {
            interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
            interaction_Info_UI.SetActive(true);
        }
        else 
        { 
            interaction_Info_UI.SetActive(false);
        }

    }
}

}

woeful leaf
#

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

peak pivot
polar marten
#

yeah...

potent sleet
pine jungle
#

what name space wich line

polar marten
#

it sounds like you started working on a game recently that is poorly engineered, and you're being asked to do something that doesn't make sense, it's not clear if it was your idea or not so don't take that personally

#

you can't tell me what platform it's on, which isn't sensitive, but you think it is

#

i am no expert, but it stands to reason if you're writing linters to work around DI, which was a fateful and bad choice, this game is going to take 10 years to develop

peak pivot
#

The overall game isn't poorly engineered but there were some early decisions like relying on dependency inject that are definitely things I wouldn't have done even 5 years ago.

polar marten
peak pivot
#

The game is already out, but not on the platform I'm currently developing against.

polar marten
#

okay i mean you can see in this chat, people talk about the switch, quest pro, various HMDs all the time here, it of course doesn't violate any NDAs

#

i'm not going to know what the game is, and it's not even going to be sensitive that a game is being released for a platform...

#

anyway, i'm not trying to raz you up on this

#

90MB is both a lot and not a lot of memory

peak pivot
#

@polar marten I'm not taking any offence to what you're saying. I think it's quite reasonable.

polar marten
#

okay okay

#

just checking

#

you can rip out DI in a week. that would be the best solution. the thing probably has 1 implementation of everything anyway

#

otherwise, i think you should generate link.xml

#

and avoid requiring [Preserve]

#

you can also simply preserve your player assembly

peak pivot
#

And yeah 90MB isn't a lot but when we only go above our memory cap with about 200MB having a simple setting that we can change to get 90MB back is very tempting.

polar marten
#

yeah that makes sense to me

pine jungle
polar marten
#

i think you should try a simple solution first, like preserving all types and members in the player assembly using link.xml or the attribute (i forget which one is for assemblies)

#

and see what happens

potent sleet
polar marten
#

you are probably going to get 90MB back from generics in a serialization library, not from your player assembly

peak pivot
#

The main thing I want to avoid is that other team members that aren't directly working on the port will commit things by mistake that causes crashes, I rather have a nice "Hey, this class is missing [Preserve] on its constructor, please add it."

polar marten
#

or freezing usage of DI

peak pivot
#

I'll look into it more as I understood it you had to be very specific for the method.

potent sleet
pine jungle
potent sleet
#

it's not tho

#

a quick googling will reveal to you

pine jungle
#

what is the language then beguse its say c+ as the language on the website i found it

deft pebble
#

C+ is not even a language tho

potent sleet
#

it is

#

it exists it neverland

pine jungle
deft pebble
potent sleet
orchid bane
#

For some reason my tiles have their colliders 1 pixel bigger than their sprites are, why can that be?

pine jungle
deft pebble
pine jungle
#

yea it say c# i am dume but still dont now how to fix beguse try everting and it still not working

orchid bane
potent sleet
#

do you know how to look it up in the docs?

#

a c# basics would help you understand what it is

pine jungle
#

no i just sarted game deving

potent sleet
#

next time

pine jungle
potent sleet
#

Anyway, You should probably learn about TextMeshPro.
It behaves exactly the same as Text component but it's now the standard text and Text is Legacy

orchid bane
#

@deft pebble could you help me with it?

potent sleet
orchid bane
#

๐Ÿ‘น

potent sleet
deft pebble
polar marten
orchid bane
#

If I had to say, it's very imprecise, but I don't know why...

#

Here's like a 13x13 selection

potent sleet
orchid bane
#

bruh

#

okay

potent sleet
#

nOt A cOdE qUeStIoN

ancient sable
#

how to reduce amount of gameobjects in a 2d game? I'm trying to make a game similar to terraria just for fun and I havnt ran into the issue yet but I do know that once im trying to make an actual world (and not just this small testing area for debugging while making it) having every block be its own gameobject will be way too laggy. Is there any way to try to reduce the amount of gameobjects im using for the world while still being able to interact with each tile (just the size of a 1 by 1 square) separately. Also are 2d gameobjects more efficient than 3d ones?

deft pebble
#

Also, not sure in 2d, but minecraft just generates all blocks as a single mesh, you probably could use this approach in 2d too

ancient sable
ancient sable
deft pebble
#

But having a huge array of structs still would be much more efficient then having tons of gameobjects

deft pebble
#

I remember I saw a vid where someone explained how terraria managed to have this insane count of tiles, let me check

#

It's not Unity related, just a general concept

ancient sable
#

Ok. If you could send me that if you find it please send it, and thanks

hexed pecan
thick socket
deft pebble
#

Yeah, and chunks are connected into single mesh iirc

thick socket
#

(idk anything about chucnks or meshes)

ancient sable
thick socket
#

seems like learning that stuff might be smart down the line

potent sleet
#

Catlike coding or Red has good articles

#

I think sebastian league did one as well but cant recall exactly

deft pebble
# ancient sable Ok. If you could send me that if you find it please send it, and thanks

I think it's this one @thick socket
https://www.youtube.com/watch?v=YIDbhVPHZbs

I'm a professional programmer who works on games, web and VR/AR applications. With my videos I like to share the wonderful world of programming with everyone!

DISCLAIMER:
This video is not actually representative of how Terraria works. The research I did for this video turned out to be inaccurate and inadequate for the purpose of this video. ...

โ–ถ Play video
thick socket
#

lol

hexed pecan
#

Nice video title

thick socket
#

the title says "Redacted: Mostly inaccurate" ๐Ÿ˜ญ

deft pebble
#

yeah... back when I watched it, it wasn't redacted ๐Ÿ˜„

thick socket
#

xD

deft pebble
#
4:48 - Chunks? Yeah, Terraria has none of that. At all. It never did. It just uses a giant Tile[,] array, which is idiotic, but works for vanilla version of it.```
#

In the comment section

#

The huge "redacted" comment is actually pretty useful

woeful leaf
#

How come this script also grabs the parent's rect? Shouldn't it only get the children's rects?

using UnityEngine;

public class SpaceOutTest : MonoBehaviour
{
    [SerializeField] private Vector3 space;
    private RectTransform[] rect;

    [ContextMenu(nameof(SpaceText))]
    private void SpaceText()
    {
        rect = GetComponentsInChildren<RectTransform>();

        for (int i = 0; i < rect.Length; i++)
        {
            rect[i].localPosition += space * i;
            print(rect[i]);
        }
    }
}
main shuttle
woeful leaf
#

That doesn't make sense does it?

main shuttle
# woeful leaf But why?

I only knew those functions were like that. I have no idea why they do it this way of course, seems rather unintuitive.

woeful leaf
#

seems rather unintuitive
Yeah I'd say the same, it's confusing as balls

#

So how can I make it that it doesn't take the parent then?

main shuttle
#

Regardless it takes it. So you need to skip it in the foreach

woeful leaf
main shuttle
#

Seems risky, you could just do if gameobject != rect.gameobject

main shuttle
#

It says nothing about sorting, if you want to take that risk that's fine by me. I have no idea if IL2CPP for example would give a different result then mono then or whatever.

light wraith
# woeful leaf Why's that risky

the first object isn't for sure the parent + you could accidently have the component removed or use this script on a different object and miss it.
generally it's just bad practice

woeful leaf
light wraith
#

so it's just a save 1 line to check for the game object

woeful leaf
#

So it's not a real big risk

main shuttle
#

if gameobject != rect.gameobject = no risk ๐Ÿ™‚

woeful leaf
main shuttle
#

But you do you

light wraith
#

it can be an annoying bug that you will find in a later debug

light wraith
woeful leaf
#

What if I just do that if, and remove it from the list if it succeeds?

main shuttle
#

Many ways to go about this.

woeful leaf
#

I suppose

#

Thanks for the help :)

main shuttle
woeful leaf
#

This works now :D

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

public class SpaceOutTest : MonoBehaviour
{
    [SerializeField] private Vector3 space;
    private List<RectTransform> rect;

    [ContextMenu(nameof(SpaceText))]
    private void SpaceText()
    {
        rect = new(GetComponentsInChildren<RectTransform>().ToList());

        if (rect[0] == (RectTransform)transform)
            rect.Remove(rect[0]);

        for (int i = 0; i < rect.Count; i++)
        {
            rect[i].localPosition += space * i;
            print(rect[i]);
        }
    }
}
pearl swallow
#

So, I'm trying to have bullet swapping based on my character's typing. The bullet prefabs are different instances. Below is how I organized it in update:

 if(boost>=100 && slimeType == 1)
        {
            projectile = GameObject.Find("FlameBullet");
        }

        else if(boost>=100 && slimeType == 2)
        {
            projectile = GameObject.Find("IceBullet");
        }

        else if(boost>=100 && slimeType == 3)
        {
            projectile = GameObject.Find("RockBullet");
        }

        else
        {
            projectile = GameObject.Find("SlimeBullet");
        } 
woeful leaf
#

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

pearl swallow
#

Saw the 3 tick thing after I posted.

main shuttle
pearl swallow
woeful leaf
#

@main shuttle

#

Only learned it recently as well :P

woeful leaf
tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
main shuttle
woeful leaf
#

:D

muted zealot
#

on another topic, i am trying to have my gameObject stand on a tree (this is a squirrel controller if ur wondering). so i am casting a ray from my position to the tree and setting my rotation to the normal of the hit. does anyone see a problem with this approach or even have a better one?

                Ray ray = new Ray(transform.position, toTree);
                if (Physics.Raycast(ray, out RaycastHit hit, 5, LayerMask.GetMask("TallVegetation")))
                {
                    if (hit.collider.gameObject == targetTree)
                    {
                        transform.rotation = Quaternion.Euler(hit.normal);
                        //body.AddForce(-hit.normal);
                    }
                }```
woeful leaf
pearl swallow
#

There/

main shuttle
pearl swallow
#

Yes

main shuttle
pearl swallow
#

I want to swap the prefabs into that "slot".

#

I want to, but I have multiple prefabs that I'm trying to swap in, but I don't remember how to.

main shuttle
#

So you have 1 slot Projectile, and you want to put different bullets in it?

pearl swallow
#

Yeah. Projectile is the "holder" so to speak to house what type of object is shot.

main shuttle
#

So an array of prefab Bullets, you could also just serialize them independently if you would want. Doesn't really matter much with 4 types.

pearl swallow
#

Alright, thank you, that should help me narrow the search.

devout lodge
#

hi, I have a prefab with child objects, but if I instantiate this prefab, it only creates the parent gameobject. how can I fix this?

leaden ice
#

or the children are being destroyed by your code right after being instantiated

devout lodge
#

i also tried by setting it as a gameobject instead of a prefab, but same result

swift falcon
#

Asking again how can I make a Navmeshagent not decelerate instantly when reaching its destination

leaden ice
#

There's no way to duplicate it WITHOUT its children

#

show your setup and your code

#

and prove me wrong

devout lodge
#

then i am confused because the gameobject definitely has children

leaden ice
#

but I think you've just set something up wrong

leaden ice
#

show everything

devout lodge
#

ok wait

leaden ice
#

this is not a prefab

devout lodge
#

yes i said i tried with prefab, then with gameobject

leaden ice
#

where does this take you

#

(make sure project window is open when you click it)

devout lodge
leaden ice
#

does it take you to somewhere in the project window? Or to the object in the hierarchy

leaden ice
#

the AI Snake object

devout lodge
leaden ice
#

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

devout lodge
leaden ice
devout lodge
#

nope

#

just a sphere collider

leaden ice
devout lodge
leaden ice
devout lodge
#

yes

leaden ice
#

can you show that

#

probably that script is destroying it

devout lodge
#

perhaps it is the 'RemoveSnakePart' method

#

debugging now

leaden ice
#

I think it's almost definitely something in this script

#

DestroySnake is running perhaps

devout lodge
#

yeah

devout lodge
#

oh youre right

#

weird thanks

leaden ice
# devout lodge weird thanks

seems like you have two bugs then:

  • DestroySnake is running when it shouldn't
  • DestroySnake is not destroying the entire snake, it's leaving that top level object behind
devout lodge
#

so just gonna make sure that doesnt happen

#

thx for the help :)

leaden ice
bitter trout
trail mist
#

sorry for posting here but can anyone tell me why is my game build on black screen ?

#

i made another scene (this one) just to test and still same problem

leaden ice
potent sleet
#

also not a code question

bitter trout
leaden ice
bitter trout
#

Yeah i know, i did not find a different solution

leaden ice
#

all you need is a hinge joint correctly anchored at the position you grabbed it from

#

generally you'd also create an invisible kinematic Rigidbody at the mouse position, and use MovePosition in FixedUpdate to make that invisible object follow the mouse

#

that will give you realism

#

attach the hinge joint to the invisible object

#

you'd also need to use theBox.transform.InverseTransformPosition to get the correct local space position for anchoring the joint

trail mist
potent sleet
trail mist
potent sleet
trail mist
#

i removed all the scenes and made a new empty one to see if the problem is only in specific scenes or in all of them

potent sleet
#

what about Game View

#

not the Build

trail mist
#

here is it

potent sleet
# trail mist

do you have any compile errors when exporting? have you tried another scene too

#

does only happen in build or in Playmode too

trail mist
#

i got these warnings for the first time, for shaders that are NOT used in this scene

#

i'll try removing them and building

potent sleet
#

maybe, they are just warnings and for shaders you may not use but yeah try

trail mist
#

i really got shoked this morning when i tried to build for the fist time

#

UI elements renders but anything else dont

potent sleet
#

are you on a laptop or something

bronze rampart
trail mist
#

not the first time i did build a unity game on it

#

but first time igot the black screen

#

removing those shaders didnt help still black screen

potent sleet
trail mist
#

this scene also has no shaders since its a default skybox + cube

#

i'll update my graphics

potent sleet
#

have you tried, new blank scene, different camera , no post processing

#

start eliminating one possibility after another, debug

bronze rampart
#

@trail mist assuming a blank scene with just a camera in it renders as expected can you try and narrow it down a little more. for example go to ur scene and disable everything then re enable things one at a time until the problem re appears. its a bit brute force as far as trouble shooting go's but you didn't give much info

trail mist
#

i got this warning after building the empty scene

bronze rampart
#

does it render as expected though?

trail mist
potent sleet
dusky coral
#

hey im having trouble with lerp basic lerp stuff i would assume

leaden ice
potent sleet
#

ah yes

leaden ice
#

which is exactly what the error will say

bronze rampart
# trail mist no. black screen

ok ya try and address the warning. Im not sure specifically how to fix that off the top off my head but that would be my next step if it was me

potent sleet
#

no Idea what I read those as Transforms xD

potent sleet
#

if they are talking about the Player that runs on your PC to run the game

dusky coral
leaden ice
leaden ice
#

you never created t, so t does not exist

dusky coral
#

thank you

potent sleet
#

what threw me off is you kinda wrote it correct the firs time xD @dusky coral

#

except for t

dusky coral
#

would {SerializeField} private flot t;

potent sleet
#

you still need the t to move

#

like t += Time.deltaTime

#

but this isnt correct way

#

the link I sent you show example how

dusky coral
#

ok thank you

trail mist
potent sleet
#

it's not the burst compile

trail mist
#

ill reboot real quick brb

potent sleet
tepid river
#

im trying to import my monobehaviour into my unit test, but i cant figure out how.

using System.Collections;
using NUnit.Framework;
using UnityEngine.TestTools;


public class NewTestScript
{
    // A Test behaves as an ordinary method
    [Test]
    public void NewTestScriptSimplePasses()
    {
        // Use the Assert class to test conditions
    }
}

separate file:

using System;
using UnityEngine;
public class ShipPlayerInput : MonoBehaviour
{ ... }
#

it doesnt know ShipPlayerInput by default in the test script and i cant figure out what to import

trail mist
#

i have this projects that have similar shaders so ill try

#

it will take some time so brb

leaden ice
#

And/or didn't create the test assembly and/or game assembly in the first place

tepid river
#

the first one

#

thanks, can finally import.
am new to this whole dotnet show

distant glen
#

Question regarding ScriptableObjects:

Pictured is a ScriptableObject I have created as it appears in the Unity inspector. It is created from a class called Item that inherits ScriptableObject. I have created this Item from the Create Asset Menu, and put in a few details relevant to this item.

The Item class has an enum called "ItemType", and by selecting "Seed" from the drop down menu in the inspector, this particular Item's itemType is set to "ItemType.Seed".

I want to display different values to be modified in the inspector based on the "itemType" that is selected by the user. For example, "ItemType.Weapon" might have variables that I want to change in the inspector called "attack" or "speed", however, "ItemType.Seed" would have no use for something like this, so I might want variables such as "growthRate", or a bool like "canPlant" to be visible in the Inspector instead.

I might be going about this the wrong way... it might be better to create an entirely new script with a class called "Seed" which inherits "Item". So rather than having one "Item : Scriptable Object", I would have other scripts like "Seed : Item", and "Weapon : Item" which are still items, but have their own functionality.

What do you think?

trail mist
#

life update : tried another project, and it's fine even with those shaders that i deleted, animations plays sounds are ok everything is ok

trail mist
#

and try again

west cobalt
#

this might be dump but i literally dont kniw how to get startet with unity
all the tutorials start with some done code (ofc not everything) but while reading/watching that i still have no idea how to start from scratch and all the stuff
are there any tutorials that arent like 5 years old but explain this whole thing

trail mist
#

understanting them first will make you better since you will understand what the videos do sometime

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/

west cobalt
somber nacelle
polar marten
#

don't use scriptable objects to compose behavior. use prefabs

#

where did you get the idea to use scriptableobjects?

distant glen
# polar marten where did you get the idea to use scriptableobjects?

I have a bunch of items in my game. These items have different values, such as what they are worth, their descriptions to display in the inventory, the sprite to display in UI etc.

If I wanted to instantiate one of these items in the scene, then I would create a GameObject, and that would copy over the values of the ScriptableObject relevant to it.

I got the idea watching Brackey's tutorial for an Inventory system.

polar marten
#

instead

#

make a prefab

#

and instantiate the prefab

#

which is even simpler

#

and easier

#

and better

#

in every conceivable way

#

that you could possibly fathom to dream or imagine in your mind

#

and never make scriptable objects again

#

ever, in all of history, for the rest of your life and afterlife

#

then you owulnd't have to copy relevant values. it would Just Work

#

there's no copying

#

and you can compose scripts

#

to do all sorts of things

distant glen
#

Confusion. Why are ScriptableObjects implemented in the first place then? They seem like a good alternative to JSON or XML

polar marten
#

see "Reason #1"

sinful juniper
#

Hello, I don't know if my problem comes from code or Unity, I'm quite new in Unity and i'm having objects where I can't set the value :

public GhostBehavior initialBehavior { get; private set; }```
I have this script member in Unity
polar marten
hexed pecan
leaden ice
#

As a beginner they should start with learning the basics.

#

Just use a regular field

sinful juniper
#

(sorry for the wrong channel) thanks for the answers, I'll do the tutorials I just have a project I have to submit soon and I didn't have the time to make all the tutorials I'd liked ^^"

leaden ice
leaden raven
#

whoops didn't know that channel existed

fallen lotus
#

is something like this possible with function parameters? I know this specifically isn't possible but i'm trying to do this.

        public void LoadScene(string sceneName || int sceneIndex)
        {
            PlayerPrefs.SetString("sceneToLoad", sceneName || sceneIndex);
            SceneManager.LoadScene("Loading");
        }
simple egret
#

No, you can't make variable types. You can make an overload though, ie. two methods named the same but with different parameter types

fallen lotus
#

thank you!

#

also is it possible to retrieve the version number via code from the player settings?

simple egret
#

A quick Google says it's Application.version

grim pebble
#

In order to teleport a character controller, you must first disable the CC, then change position, then re-enable. Otherwise the teleport fails. However, disabling character controller doesn't fire OnTriggerExit on triggers the CC is currently inside of

#

So teleporting a CC out of a Trigger doesn't trigger the exit call

#

thinkPeepo how to deal with this

simple egret
#

See if teleporting without disabling notifies the trigger exit. Just call Physics.SyncTransforms() right after you change the position to avoid the CC from rolling back

grim pebble
#

Oh, nice, wasn't familiar with that call. I am sure that will work, lemme see

#

Yeah that works, nice! I was never thrilled about the disable/enable thing, didn't know there was a more appropriate way to do it. Thanks Okayge

vale wharf
#

How can I get the position of a UI element inside a scrollrect relative to the content object?

#

take the red rectangle for example. At it's default position it should have a relative position of 0, which should go negative as I scroll up

deep fable
#

Is there a way to check if a GameObject has at least 2 instances of the same script monobehaviour attached? (Basically when a script needs to remove an effect on the GameObject it is attached on but only if there aren't other instances of the same script)

I could use GetComponents and check the length, but is there a better way?

grim pebble
#

My instinct is that using whole components to represent individual effects might not be entirely how they are meant to be used, at least that's my understanding thinkPeepo

#

I don't think you are supposed to be adding/removing components on the fly all that much thinkPeepo

#

I've modded a handful of mainstream unity games and poured over their code and I have never seen a component be added or removed at runtime

grim pebble
vale wharf
#

why even have a code channel then

grim pebble
#

I didn't say you can't ask the question here Shrugeg Just seems like nobody here at the moment knows the answer, but those other channels might have someone who does Shrugeg

thick socket
#

I should be making 100+ prefabs depending on the item?

deep fable
grim pebble
thick socket
#

or use it to increment timer

grim pebble
grim pebble
#

Like at runtime, for all users of that SO ?? WTFF

thick socket
#

I've got a list of like Items and everything...pretty sure this would be rough to do in just code

thick socket
grim pebble
#

This isn't at runtime though this is at editor time

thick socket
#

I just use SO as like a template for data I will use later

grim pebble
# thick socket

At the very least why not split them into separate SO files

#

Having it all in one file seems particularly annoying to work with

thick socket
#

I mean

grim pebble
#

In a list like that, can't like duplicate easily and stuff

thick socket
#

its 1 SO that just holds all my items

grim pebble
#

It's just like a library of those items, right? You're not changing those items at runtime?

#

At runtime means, during the game

thick socket
#

right

#

(at least not atm)

grim pebble
#

thinkPeepo I think that is how you are supposed to use SO's

thick socket
#

correct

grim pebble
#

But putting it in one as a list like that seems a bit clunkier than having a folder of separate files for each item

thick socket
grim pebble
#

Yea

thick socket
#

seems easier to just store it in a list

grim pebble
#

As opposed to a list with hundreds of entries, what's the difference?

#

Idk I'd rather work with file explorer than unity inspector heh

thick socket
#

fair

grim pebble
#

You can sort and stuff Shrugeg

thick socket
#

but its a lot more you need to load at runtime for one

#

you can write code to sort your lists and fill things in inside SO

#

like a one-off

grim pebble
thick socket
#

I filled in like the Sprite name/helmet name

grim pebble
#

I'm guessing you're not using version control HmmgeSit

thick socket
#

then in code set id to go through and set the super long ID to data about it from elsewhere

grim pebble
#

But you are 'sorting' the file which means changing it

thick socket
#

right, just did that like once or twice

#

then got rid of the script code and the SO saved all the data that was set

#

which is why some people use it to store data

#

cause it can be set in code and stays when you stop playing

grim pebble
#

I'm not disputing using SOs, I'm not sure what the hate is for when they are used correctly

#

I'm concerned about the single-file format you're using PeepoShake

grim pebble
#

It hackles every instinct I have

thick socket
#

that github said it hates it xD

thick socket
#

make a list that stores all my data

#

and go grab it when I need it

grim pebble
#

That github is garbage take

#

Conclusion

โŒ DO NOT USE ScriptableObject Architecture โŒ

Only use ScriptableObject when you need immutable data asset. If possible, don't use it at all. Editing design data with Unity Inspector is horrible. Use better alternative for this too, such as using Spread Sheet.

#

This take is awful

#

Use a spreadsheet ??? WTFF

#

Either you are using SO or GameObject

thick socket
#

yeah, hes got some awesome spreadsheet, haven't bothered figuring it out yet tho

grim pebble
#

Either way you are editing design data with inspector

thick socket
#

if there was a youtube video showing like HOW to use his spreadsheet I would probably instantly start using lol

grim pebble
#

I certainly would not

#

Separate files are good, editing with inspector is fine, git ingests GameObject and SO files just fine

tender fog
#

uh how do I rotate something

thick socket
grim pebble
tender fog
#

i was ignored in the beginner chat

grim pebble
#

There's also something like FaceTowards

tender fog
#

ok ty

#

idk why that didnt appear on google lol

thick socket
thick socket
# tender fog idk why that didnt appear on google lol

ex)

protected void Flip()
    {
        character.transform.localScale = new Vector3(-1f * character.transform.localScale.x, character.transform.localScale.y, character.transform.localScale.z);
        facingRight = !facingRight;
    }
tender fog
#

im not sure what that means but I shall take that into account

thick socket
#

๐Ÿ˜„

tender fog
#

thanks for the help

#

for 2d should I use Z?

grim pebble
#

I don't think ya have z in 2d

#

I never touched 2d SHRUGGERS

fluid lily
#

If I have one array of objects and I know they can be cast another type, can I just do (Components[]) for example to cast each element of the array?

tender fog
#

i tried all of them in the editor and Z was the only one that moved them

grim pebble
#

Casting the array like you suggested will fail because an array's contents type doesn't effect the array's own ... castability? lol

bitter trout
grim pebble
#

One day I'll just type Destroy(gameObject) instead of Destroy(this) on the first try Okay

uncut vine
#

Hi all. I want to iterate on gameobjects and animate (animator.SetTrigger) them in order. This doesn't seem to work, the order is not kept. Any direction on how to do this?

leaden solstice
leaden ice
#

uhhh it is?

#

what happens if you then do myObjArray[3] = 5;?

leaden solstice
#

You get runtime exception ๐Ÿ˜„

leaden ice
#

I see

leaden ice
#

this is the inverse of what @leaden solstice was illustrating right?

#

E.g.

object[] myObjArr = new[10];
string[] myStrArr = (string[])myObjArr;```
#

this is not a valid cast

leaden solstice
#

Yeah that's illegal

#

I'd go with IEnumerable<string> myStrEnumerable = myObjArr.Cast<string>()

thick socket
#

seems really useful but not super easy for me to figure out ๐Ÿ˜„

somber nacelle
leaden solstice
somber nacelle
#

ah right, misread it lol

leaden solstice
#

I'm happy to help you adapting it tho

vale wharf
thick socket
#

Ill probably reach out to you sometime if I run into issues ๐Ÿ™‚

drowsy maple
#

I need to copy components at runtime, which requires going through all the fields of a component and filling in the values from the original. But you can only do that once you have created the new component with AddComponent<>(), but by then it's already too late because that will call Awake() immediately on the new object which will inevitably access fields that you had no chance to initialize because they didn't exist up until that exact moment. Is there no way to add a component at runtime without also invoking Awake()?

bitter trout
leaden ice
#

Why aren't you using a Hinge Joint

bitter trout
#

Im

#

What do you mean?

#

Ah know i know what you want me to do

#

I dont know if it will give me the correct results but i will try

misty jewel
#

@plucky inlet just a tiny update after all that, I realized the package already has an array that contains the selected objects birdoah I only noticed the next day and I feel dumb

leaden ice
#

hinge joint seems more appropriate

bitter trout
plucky glade
#

Hi everyone! I just ran into a problem trying to use visual studio 2019 (I've tried both the "community" version and the manual installation version). Basically, I can open up the code editor while developing a project. Everything's normal, the thing is, every time I hover any text/code in the code editor, it will just crash, no message or anything, it just hangs and closes. Any ideas what could I do to fix this problem?

-Some important information
-I've not opened my unity project in 3 months, however, it doesn't just happen with this one project, it happens with older ones as well.
-by hovering any text/code, I mean putting my cursor over any of the code you would normally write in the editor, instead of showing some tooltip, it just hangs and closes.
-I've not updated either the unity version I'm using for all my projects nor my visual studio 2019, however upon encountering this error I've tried updating visual studio, same error.

I'm going to try uninstalling visual studio 2019 and let unity reinstall it for me and see if that fixes it.

Otherwise any possible solution you could suggest is appreciated

bitter trout
#

btw, should i put the hinge joint onto the grabbed object or the mousefollower

polar marten
bitter trout
drowsy maple
#

@polar marten thanks for the tip but that won't do unfortunately, I need the component to end up on another, pre-existing gameobject because the component requires that exact rigidbody. Can't change how the rigidbody is accessed either since the component is from an asset and not my own.

polar marten
leaden ice
polar marten
#

you better start believing in making changes to assets

drowsy maple
#

i thought about that too, but that usually causes more trouble than its worth as you go down the rabbithole of refactoring the asset , especially if you want to keep updating to newer versions

leaden ice
drowsy maple
#

i just settled for deactivating the destination gameobject right before the copy and then reactivating it

#

that also prevents awake from being called and doesn't seem to have any side effects from what i can tell

plucky glade
bitter trout
shell scarab
#

hello, could someone explain to me why ~0 == -1 is true? I would think ~0 is equal to -2,147,483,648, since all bits are flipped.

bitter trout
#

Ah, im sorry didnt see youre on idle

bitter trout
odd zenith
#

ok so im learning perlin noise

#

and i accidentally made it do this

#

its cool but idk why it does that

#

ill shwo code in a sec

leaden ice
#

Looks like your standard perlin noise sampling to me...

odd zenith
#

yes but

#

why when i move the script holder up the thing doesnt move up it just makes waves? the tiles are transform.parented to the script holder object (empty gameobject)

leaden ice
#

the parenting doesn't matter

odd zenith
#

o

#

how do i make it like

leaden ice
#

set local position instead of world position

odd zenith
#

adhere to the parent

#

how?

leaden ice
#

use .localPosition instead of .position?

odd zenith
#

o

#

i didnt know that was a thing thank u tho

#

now it's sliding around n stuf its being goofy

#

like moving up is fine the whole thing moves up

#

when i move it to one side or the other it slides a lot like stays intact but doesnt move with my mouse

#

im just tryina figure out why it works like that

#

ok well i fixed it by using local pos when i get the x and y variables, but i stil don't entirely get why it works

distant glen
#

How can I stop a coroutine and restart it?

Image 1: Coroutine is assigned to a variable and called on Awake()

Image 2: Coroutine instructions

Image 3: The method I call to reset the coroutine.

It seems that once stopped and restarted, the old coroutine keeps running to some degree. It does not truly "reset".

leaden ice
#

The old coroutine will not keep running, no

#

Are you asking about the soil resetting to the "fertile" state or something?

distant glen
# leaden ice I don't even see anything in the coroutine that's different. What does "resettin...

When the coroutine starts, a function is supposed to be called between 10 and 20 seconds.

This functions as normal.

However, after resetting the coroutine, the function seems to be called between 2 - 3 seconds, or earlier than expected, as if the coroutine that was stopped previously continued to execute its code.

Resetting it, in this case, means resetting the timer before the DegradeSoil() function is called.

If the next time that the DegradeSoil() function was going to be called in 13.6 seconds, the ResetSoilDegradation() method should reset the timer to zero, and assign a new number between 10 - 20 seconds for when the DegradeSoil() function will be called.

leaden ice
#

Maybe share the rest of the code?

north moss
#

Hi, I asked ChatGPT about using Events, but Im sure something is missing, here's a part of my code:
Basicly I just want my code to put a string into my console. It's just for Debug.Log yet
Also, I thought we had a way to put text into discord as code? I looked at the read me but it's not there. Was it removed or it's the wrong channel? XD
CreerEchiquier has no use for the clicking, it's not revelant to my question

void Start()
    {
        Debug.Log(gameObject);
        EventTrigger trigger = gameObject.AddComponent<EventTrigger>();
        EventTrigger.Entry entry = new EventTrigger.Entry();
        entry.eventID = EventTriggerType.PointerDown;
        entry.callback.AddListener((data) => { Debug.Log("Hello"); });
        trigger.triggers.Add(entry);
        CreerEchiquier();
    }
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.

distant glen
leaden ice
#

why do this in code

#

instead of just configuring the event trigger in the editor

quaint rock
north moss
quaint rock
#

you can literally just implement a pointer handler, or drag something into the event trigger instead

north moss
#

I can't make it as a prefab, it's created via GameObject.CreatePrimitive

leaden ice
leaden ice
#

you can also just write your own script that implements IPointerDownHandler and add that instead of this weird hoop-jumping with EventTrigger as well

north moss
#

I could... I didn't want to XD, but I guess I should lol...
So it needs a collider? argh... I think that's gonna be hard to click on it XD
I want to click on one of these Quad when I need to

quaint rock
#

i have never used EventTrigger once from code

#

its really just a thing meant for persistent listeners, better way to do it in code at runtime if needed

north moss
#

Okok

#

Thanks for all the info

north moss
#

Well, I understood why my OnMouseDown wasn't working tho! It has to be from a script attached to the gameObject. (I made a script making PrimitiveType without being linked to the GameObject). Basicly a non-Monobehavior was acting as a ghost-component of my object. I thought I could still use it that way but it seems I was wrong

tough osprey
#

Does C# treat "const int" differently from "int" because it knows it's value?
Here's two ints initialized, one as a const:

private const int kNumInstances = 3;
public int NumInstances = 3;

Trying to use the Public int instead of the const int I get a conversion error

quaint rock
#

well read the error, something is a long and you are using a uint

#

but no adding const just makes it constant

#

type is still int

tough osprey
#

... no, they're the same exact lines. The only difference is the final variable on those lines. kNumInstances is a const int, and NumInstances is just an int.

quaint rock
#

it might be because it knows its posititve if constant

#

but i doubt its that smart

tough osprey
#

If I change the Test 2 line to kNumInstances also, the error goes away, even though both kNumInstances and NumInstances are both ints.

#

My guess is that it actually is smart enough to know the kNumInstances is 3 and only ever 3. So the formula of "uint + 3 * int" will safely always be a uint? Whereas replacing "3" with some unknown int makes it riskier? Though by that logic, any uint + uint could exceed the capacity of a uint, so not sure

quaint rock
#

yeah would have to look into the resulting il more

#

if its doing that, it really kinda feels like doing a #define NumInstances 3 in C

tough osprey
#

although the other int in that formula is also a small constant so everything there is all already known at compile time (I want to make it dynamic :P)

quaint rock
#

well if dynamic just do the casting yourself as needed, or do not create a situation where you mix int types, and just do it all as long

tough osprey
#

yeah ... this is dealing with memory address stuff which I'm still wrapping my head around (BatchRendererGroup) so I didn't want to mess with types, but will give casting a shot

#

This entire sample code blows up a ton by trying to make it dynamic

#

Fixed it

potent glade
#

hi everyone, I am making a plugin for my webgl app:
I am using this function (java script)

GetArgs : function()
    {
        let source = document.getElementById('player').src;
        return source ;        
    },

but I am getting an error when returning the value... I want the src to be returned as a string... can someone help me know if I have to do something before returning the variable?

trail sinew
#

how would I add mass to this equation?

west lotus
#

-gravity* Time.deltaTime/mass

unique trout
#

So, I'm playing around with Jobs, specifically parallel jobs. I'm wondering if it's possible to add new jobs to a parallel job struct before it completes, or if I can only create a vector of them, removing the completed ones as they finish.

west lotus
#

Also pretty sure you dont need the second * deltaTime when calling Move you are already factoring it in the vel calc

west lotus
unique trout
#

Basically, on one frame I set up a ParallelJob struct and start it running. It probably won't finish on this frame, so I let it run, storing the ParallelJob in a static variable, then checking every frame if the jobs have completed and doing with the data what I need. However, it's entirely possible that before the ParallelJob completes, the player has done something which requires more of that same type of data being generated.
So, basically, can I add to the ParallelJob after it's started, or do I just create a new one, and make the static variable a vector of ParallelJobs?

#

Oh, and by Vector, I meant List. Bleh, too used to working in C++.

west lotus
#

Its not advisable to read and write to the same collection especially for a paralel job. There is a way to disable the restrictions but you will have to manage your offsets carefully. I suggest simply scheduling another job with the new data and aggregating on the main thread.

unique trout
#

Alright. Figured that'd be the case, but wanted to know.

trail sinew
west lotus
#

You need to divide by mass

trail sinew
#

but multiplying seems to make it go faster

trail sinew
west lotus
#

Well yes. A object with more mass is harder to accelerate

#

Thats how physics works

trail sinew
#

wont it go faster in earth

#

cause of air resistence

#

im not the best in physics

plucky inlet
# trail sinew cause of air resistence

you are mixing up acceleration and gravity here I think. If you want to move an object with the same "force/speed" as another and the mass is higher, its going to be accelerated slower then the lighter one. Your gravity is just another force that is affecting the acceleration. In gravity, all masses fall equally if their size is the same, otherwise you would be right with your air resistence.

woeful leaf
#

In theory the TryGetComponent should not run if button is not null, correct? (Due to it being && and not &)

 if (button == null && !TryGetComponent(out button))
#

Or does only doing it like this

if (button == null)
  if (!TryGetComponent(out button))

achieve that?

plucky inlet
rain minnow
plucky inlet
#

the second one would be what you expected

woeful leaf
#

Doesn't it only do that if it's &

rain minnow
#

you're doing if button is null and if there is no component . . .

plucky inlet
#

Basically its asking the same thing twice

woeful leaf
#

It's in an OnEnable so it gets run whenever the object is enabled again

rain minnow
woeful leaf
#

And I assume TryGetComponent is more performance heavy than just checcking if button is null, no?

#

I also don't want it to reassign it for no reason

rain minnow
#

& will check both conditions, regardless if the left-hand side is true . . .

woeful leaf
rain minnow
#

yup . . .

woeful leaf
rain minnow
woeful leaf
plucky inlet
#

Thinking about it, I think I used something like

if(object != null && object.Value == 1)

And that did not give me a null reference if the object was actually null, so its not checking the second statement in the if brackets when the first is already false here?

rain minnow
# woeful leaf You mean will run?

nope, it will only run (check) the second condition if the first condition is true. the first condition is if button == null . . .

woeful leaf
#

I mean yeah but it does the same for both, no?

plucky inlet
#

No, if your button == null, it will never try to check your component, but if its in the same statement, it will check if its null and if you do not have the component

#

Which makes me wonder again, why my if statement up there is working ๐Ÿ˜„

woeful leaf
#

TryGetComponent does not run if the button is not null

 if (button == null && !TryGetComponent(out button))

And here TryGetComponent also does not run if the button is not null (Again, due to the difference between & and &&)

if (button == null)
  if (!TryGetComponent(out button))
#

Or is this what I'm saying still wrong

woeful leaf
#

Or am I missing something big here

plucky inlet
#

TryGetComponent will run, because you want the if statement to check if BOTH are being met. You only run the code if both are correctly returned. I am not sure it is foreseeing the next argument in your if statement. Let me test this real quick ๐Ÿ˜„

woeful leaf
#

&& can do that because if the first condition is false, it does not matter what the value of the second condition is

plucky inlet
#

Thanks for clarifying. But then, your statement all the way up is correct. ๐Ÿ˜„

woeful leaf
#

There was a stackoverflow post that explained it well, as well, but I can't find it anymore

plucky inlet
#

I am so used to handle if with always double char statements ๐Ÿ˜„

woeful leaf
#

Or do you mean something else

woeful leaf
#

doubling it up is just more performant

plucky inlet
plucky inlet
rain minnow
woeful leaf
#

Yeah so what I said is correct, right?

rain minnow
#

the wording makes it difficult to understand, so i changed it . . .

#

if the button is found, the 2nd condition will not run . . .

woeful leaf
#

Yeah exactly, which is what I want because I don't want it to re-assign or even run a TryGetComponent if the button already has a value

woeful leaf
#

(Same logic applies)

thin aurora
woeful leaf
#

If button is null the statement will short-circuit since it's already false
Wouldn't it be true in this case?

thin aurora
#

Dunno what you mean with & since logical and is not valid here as far as I know

thin aurora
#

If you want it to short circuit, change && to ||

thin aurora
#

Try it, maybe it is

#

I don't think a logical and is valid

#

I think in this case it will do a bitwise operation with the results of TryGetComponent and button == null, which makes the question if that is possible on two booleans?

#

Why don't you just use && RisitasLaugh

woeful leaf
#

I always use &&

thin aurora
#

I more mean like validity when it comes to creating an if statement if a button exists like this

#

This probably works, but it's probably not really useful

#

I think what you do now is if (0 & 0) which is false if I remember correctly

#

Or if(1 & 0) I think actually

woeful leaf
#

This appears to work fine

#

I think

thin aurora
#

Of course, what do you expect?

woeful leaf
#

I don't know you're questioning everything and confusing me KEKW

thin aurora
#

I got confused the moment you started wondering if just using & is valid pepeLaughYou

woeful leaf
#

Nonono lmao

#

Only reason I brought up & is to illustrate the difference of && short-circuiting and & not

#

I wasn't actually planning on using & or some shit lmao

thin aurora
#

Ohh

woeful leaf
#

I don't think I'll ever use &

plucky inlet
#

Same ๐Ÿ˜„ Not even gonna keep that in mind from now on! ๐Ÿ˜‰

rain minnow
woeful leaf
#

Haha

woeful leaf
sweet inlet
#

anyone konw why this script only works once, i am getting stuck at 0% the second time i try to load

woeful leaf
#

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

peak pivot
#

I mostly use it with assignment (when I don't care about short circuit) such as this

isValid &= some_expression;
isValid &= some_expression;
...
if(isValid) { ... }```
thin aurora
peak pivot
#

Otherwise I count it & and | as bitwise operators.

thin aurora
tawny elkBOT
#
๐Ÿ’ก IDE Configuration

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

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

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

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

thin aurora
rain minnow
sweet inlet
thin aurora
#

Lack of highlighting, too much highlighting

sweet inlet
#

yeah, i didnt mind that

woeful leaf
#

Thatโ€™s what I want

thin aurora
sweet inlet
#

you mean the autocomplete stuff, yeah, it just complains about the way i write variable or method names

woeful leaf
#

Stuff like Start()

thin aurora
woeful leaf
#

He just has a different color for stuff, no?

#

Which is confusing as all balls but I digress

thin aurora
#

I was put off by the way it's colored in general, but I notice the info above the classes now.

sweet inlet
#

yeah it does all of that, it just wants me to write an _ before private variable names and some other stuff i dont care about

#

is the look really that off, its the standard intelliJ look

woeful leaf
woeful leaf
mellow sigil
#

It's JetBrains Rider, not VS

sweet inlet
#

yes, i really hate the VS stuff, no offense for anyone who likes to use it tho

woeful leaf
peak pivot
woeful leaf
thin aurora
woeful leaf
#

Interesting

mellow sigil
thin aurora
#

Pretty sure vanilla VS omits the underscore in this case

woeful leaf
#

Probably

sweet inlet
peak pivot
sweet inlet
#

no, its an instance in the scene

peak pivot
#

I don't notice any other issue apart from maybe checking if loadScene.isDone is true when you start the next load that's stuck. since it would just exit the coroutine.

sweet inlet
#

i can tell you what i am doing, i have a title scene, with some settings and a button to start the game, when i start i go to the loadingScene (where this script lives) then i get to the gameScene, when i bet the game i go back to the title scene, trying to start the game again results me getting stuck at 0% progress in the loading scene

peak pivot
sweet inlet
#

i can attempt exporting it, havent tried that yet

peak pivot
#

Ok, and this script only exists in the loading scene you load to via your Menu scene?

sweet inlet
#

yes, this script only exists once in an empty object in the Loading Scene, and the loading scene is only getting startet from the title scene

#

unfortunately exporting also gets me stuck at 0%

#

interestingly it loads when i dont do it asynchronous

peak pivot
# sweet inlet unfortunately exporting also gets me stuck at 0%

Ok yeah, I might be missing something as well here. But I can't spot any errors. And what you say about your structure make sense (assuming all the other loads are LoadSceneMode.Single as well).
If you haven't done it then I would suggest break pointing it, because that might show if there is something weird going on.

#

(I also haven't done a lot of scene load recently so I might be forgetting some oddity)

sweet inlet
#

this is how i load the LoadingScene

peak pivot
#

@sweet inlet Why Unity version are you using?

woeful leaf
#

why lol

sweet inlet
#

2022.1.18f1

#

i think that was the latest version when we startet the project

woeful leaf
#

It's not an LTS though

peak pivot
#

Tech releases are supported for a year if I recall correctly?

woeful leaf
#

No idea

#

LTS is usually more stable though afaik

peak pivot
#

But it doesn't appear to be the latest in the 2022.1.x tech stream

sweet inlet
#

could be that i forgot to update

peak pivot
sweet inlet
#

i am going to try opening it with that version

mellow sigil
#

I'm guessing it's the UnloadScene part. You don't need to do that.

sweet inlet
#

yes, i already removed it

#

that was for debugging purposes, to check if the scene was loaded without me knowing

thin aurora
woeful leaf
#

I suppose yea

thin aurora
#

LTS and any other release is as stable as long as it is supported

woeful leaf
#

Fair

thin aurora
#

LTS is just guaranteed to be up to date longer

woeful leaf
#

Righty

#

When will an LTS of 2022 release actually

mossy minnow
#

yo, im trying to do layer masking with the matrix but it seems to just, not work
i have Enemy/CameraEdge unchecked, my enemy is tagged as Enemy and my colliders are CameraEdge
is there something im missing?

sweet inlet
#

changing to 1.24f1 hasnt helped unfortunately

peak pivot
swift falcon
#

it's a problem with the mesh.uvs and mesh.vertices and triangles

peak pivot
swift falcon
#

apparently the triangles array is referencing more vertices than actually exist and the vertices array isn't the same size as the uvs array

wet pumice
#

I'm having a complete brain fart, if I have a unit vector, how's best to detect which quadrant it sits in by the diagonals?

sweet inlet
peak pivot
#

The thing to remember is that you get the nearest result regardless of which "side" it's on, that's why you need at least 2 tests.

wet pumice
#

x > y works for one diagonal

mossy minnow
#

yup, the layer not the tag

#

misspoke @peak pivot

rain minnow
wet pumice
peak pivot
# wet pumice x > y works for one diagonal

You might be able to do something like treating the vector as a linear equation and check if the slope is within certain bounds. But dot product is very fast to compute and works regardless of orientation so I would recommend using that.

peak pivot
#

That's the only thing I can think of.

sweet inlet
#

when i change it to this it loads into the gameScene properly, but i loose my progress bar

mossy minnow
#

donโ€™t think so, iโ€™m in2D but i didnโ€™t see 2 separate matrices

peak pivot
mossy minnow
#

iโ€™ll check it out

#

oh man i did not see that lmaoo

peak pivot
rain minnow
mossy minnow
#

makes sense

muted grove
#

does unity compile scripts "just-in-time" and does that mean variable name length effects compilation speed

mossy minnow
#

still keep them short enough to read easily tho ^^

pine spire
#

@muted grove it can use either, though there are platform restrictions, but even then it uses intermediate language and not c# directly

muted grove
#

so variable name length in say, javascript would effect performance?

pine spire
#

I would be surprised if variable lengths actually had and effect. They might be tokenised or something similar.

muted grove
#

more characters to read to tokenize right

#

yeah but its probably negligible or something, if the projects not super massive?

pine spire
#

I mean with c# everything could be tokenized before itโ€™s compiled to run natively

sweet inlet
#

i guess i just remove the progress bar and call it a day

pine spire
#

And I donโ€™t know how common using jit is anyway

muted grove
#

thanks guys

swift falcon
#
Mesh.vertices is too small. The supplied vertex array has less vertices than are referenced by the triangles array.
UnityEngine.Mesh:set_vertices (UnityEngine.Vector3[])
Chunk:MarchingCubes () (at Assets/Scripts/World/Chunk.cs:136)
Chunk:SetBlockAt (UnityEngine.Vector3,int,bool) (at Assets/Scripts/World/Chunk.cs:229)
BlockBreakingAndPlacing:Update () (at Assets/Scripts/Player/BlockBreakingAndPlacing.cs:46)

Mesh.uv is out of bounds. The supplied array needs to be the same size as the Mesh.vertices array.
UnityEngine.Mesh:set_uv (UnityEngine.Vector2[])
Chunk:MarchingCubes () (at Assets/Scripts/World/Chunk.cs:138)
Chunk:SetBlockAt (UnityEngine.Vector3,int,bool) (at Assets/Scripts/World/Chunk.cs:229)
BlockBreakingAndPlacing:Update () (at Assets/Scripts/Player/BlockBreakingAndPlacing.cs:46)

why does this happen? the triangle to vertices ratio and vertices to UVs ratio is definitely correct

pine spire
#

And anyway - afaik with something like javascript the variables are referenced by memory addresses and even if variable name length affected declaration you would deliberately need to create a scenario where it actually mattered

swift falcon
hollow cliff
#

what downsides will I face in project if I target .net 4.x instead of 2.0/2.1 standard when targeting mobile platforms (or in general)?

potent glade
#

can someone help me with the plugin that I wrote for my webgl app?

sweet inlet
#

ok, i think i found the problem, i just dont konw how to fix it

#

i am having timer += Time.deltaTime; in my Update() and below that Debug.Log("Timer: " + timer); in unity the timer always shows 0

#

no idea why, doesnt make any sense whatsoever

#

it just never goes into the if because timer stays 0 for some reason

swift falcon
#

Hi everyone. I'm trying to make easy to use player effect system for my game, but ... i've encountered some issue which im unsure how to handle. The problem is that supposedly UnityEvents don't fire when i store my effects in non-monobehaviour type class but when i add monobehaviour to it, UnityEvents appear as plain drag'n drop scripts which disables the choice of which functions to fire on event activation.

#

And here's the code : using System;
using TimeManagement;
using UnityEngine.Events;

[Serializable]
public class PlayerEffect
{
public PlayerEffect()
{
this.timer=new Timer();
this.isActive=false;
}

public string effectName="";

internal bool isActive;

public Timer timer;

public UnityEvent OnEffectStart;

public  UnityEvent OnEffectExit;

}

sweet inlet
#

OH NOOOO, i see why, i put Time.timescale = 0f; at the end of the game, i am so stupid, sorry for wasting everyones time

tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
rain minnow
swift falcon
#

Im calling them with Interface function that connects all collectibles. OnCollect() and inside of it i do EffectsManager.instance.playerEffects[chosenID].OnEffectStart?.Invoke()

#

I've done input system with UnityEvents and it works well but that's a monobehaviour which i guess is the root of the problem

#

What i've tried is make a wrapper class for UnityEvent stored inside PlayerEffect which derives from Monobehaviour but then again it reappears as plain drag'n drop script in inspector.

#

I've heard about other types of events but this one can be serialized and that's a huge improvement. For rest of the types i guess i would have to make a custom logic for adding listeners and custom editor etc.

rain minnow
swift falcon
wet pumice
#

is there a way to stop unity recompiling every time code changes or when you create a new class and have it only do it on a button press?

swift falcon
wet pumice
#

I shall keep digging

mellow sigil
#

You can set it to compile only on command, but that isn't as useful as you might think. For example if you make that new class you can't attach it to the button before compiling it

wet pumice
fluid moat
#

Hi, I'm working with Unity and mySQL db, I made a simple project to test the workflow that get all rows of string and int from table and store a single row with same type.

At the moment, storing data generates the following error log

#

unity A Native Collection has not been disposed, resulting in a memory leak. Enable Full StackTraces to get more details.

#

anyone knows how to solve it?

potent glade
#

I am getting this error:

EntryPointNotFoundException: GetArgs assembly:<unknown assembly> type:<unknown type> member:(null)

I am using an external function from a java script plugin:

GetArgs : function()
    {
       var str = "A string passed from JavaScript to C#";
        var bufferSize = lengthBytesUTF8(str) + 1; // calculate the size of null-terminated UTF-8 string
        var buffer = _malloc(bufferSize); // allocate string buffer on the heap
        stringToUTF8(str, buffer, bufferSize); // fill the buffer with the string UTF-8 value
        return buffer; 
        }

and in my code this is what I am doing

   [DllImport("__Internal")]
   private static extern string GetArgs();

and in my function:
string abs = GetArgs();

#

can someone tell me why am getting that error , it's been hours

fluid moat
#

Thanks ill try that :]

somber nacelle
woeful leaf
#

Can I not directly update the variable with the GetInt?

#

Because it doesn't seem to work

somber nacelle
#

there's nothing inherently wrong with that line, however it's really not enough context to know what you are expecting to happen versus what is actually happening

woeful leaf
#

Well, for another variable, but it has the same code as that ยฏ_(ใƒ„)_/ยฏ

somber nacelle
#

you're assigning the returned value to bad, right?

woeful leaf
#

Yes that's what I'm trying to do

somber nacelle
#

wdym "trying" you are either assigning the value returned by GetInt to bad or not. since you did not show whether you are or not i have to ask

woeful leaf
#

oh

#

For some reason I thought if you would call it that way it'd assign it, but you actually have to do like bad = PlayPrefs...

#

Thanks

somber nacelle
#

yes because the method returns the value. it takes a string for the key name and an int parameter as the default it returns if the key is not found. it's not a ref, in, or out parameter

woeful leaf
vestal crest
#

NavMesh.SamplePosition sometimes returns infinity? why is that

wet pumice
#

do I have to manually call base.Method() when I've overriden from a virtual method on a base class in order to call it or does it get called automatically? And what if I have a variable of type "base" which I assign a value of type "child" and call the method there?

somber nacelle
#

yes you will need to call base.Method() if you want the base method to be called from the overriding method. and the child's method will be called even if the instance of the child is stored as a "base"

main token
#

hi, is there any apparent reason why this wouldn't be working? Light.intensity -= Time.deltaTime;

potent glade
#

can anyone help with my post above please?

wet pumice
#

see if it's doing anything

main token
#

yeah that's not it

#

it's behaving really weirdly

somber nacelle
main token
#

the intensity value keeps revolving around a certain range, depending on the subtraction value

somber nacelle
#

intensity can also only be between 0 and 8

wet pumice
somber nacelle
#

yes

wet pumice
#

word

main token
wet pumice
main token
#

I am

wet pumice
#

instead of mod it

#

wait..

#

that piece of code "Light.intensity -= Time.deltaTime"?

#

are you running that exact code?

main token
#

I was yeah

#

setting them doesnt work either

wet pumice
#

that'd be calling the static method on "Light"

main token
#

Light is a reference to the light component

wet pumice
#

no Light is the base class for all lights

#

it would need to be

Light myLight;
myLight.intensity...
somber nacelle
main token
#

this.Light results in the same thing

somber nacelle
#

yes

wet pumice
#

wow, the more you know

#

evidently C++ has rubbed off on me

somber nacelle
#

the only time your variable name cannot be the same as the class name is when it is inside the class you are using. so inside the Light class you couldn't have a Light member, but outside of that you can

wet pumice
#

ok well then carry on Crux, mb, still no idea why it wouldn't be working

main token
#

it's so odd, I don't see a reason for it to behave like this

#

could it have anything to do with the Metal rendering pipeline?

#

cause I'm on a mac atm

wet pumice
#

out of my depth with that but possibly? idk how maintained iOS builds of the engine are

#

that sounds

#

like a pretty fundamental bug though

main token
#

I'll test it on a windows machine real quick

somber nacelle
main token
#

Alright, I'll ask in there

#

metal was not the issue

woeful leaf
#

Does it matter to do * 0.5 or / 2?

main token
#

multiplication is generally considered to be faster than division

woeful leaf
#

So instead of / 2 I should do * 0.5f here?

main token
#

if you can guarantee that it will be a whole number, then yes

mellow sigil
#

If you multiply by 0.5f it has to cast i to float and then cast the result back to int so it's probably slower

woeful leaf
#

So I should do division then?

mellow sigil
#

to be fair it makes absolutely no visible difference

#

do whatever is more readable and logical

woeful leaf