#archived-code-general

1 messages · Page 181 of 1

harsh bobcat
#

you can do .equals for vectors it just wont work unless you have one set itself to the other

#

the if statement looped infinitely..?

buoyant zenith
#

i mean that it kept instantiating the obj and adding numbers every second until the game crashed

#

when i used that if statement

harsh bobcat
#

whats the z of your object

buoyant zenith
#

well it is 0

harsh bobcat
#

ah

#

well it loops infinitely bc you didnt add back the check that count is false

#

that if just covers distance to the point

buoyant zenith
#

oh

#

right

eager mango
#

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

public class CameraFollow : MonoBehaviour
{
private Slider cameradistance;
public Transform target;

Quaternion toRotateBy = Quaternion.identity;
// Start is called before the first frame update
void Start()
{
    
}

// Update is called once per frame

void LateUpdate()
{
    toRotateBy.eulerAngles = new Vector3(70, 0, 0);
    transform.position = toRotateBy * Vector3.forward * -(cameradistance.value) + target.position;
    transform.LookAt(target);
}

}`

#

im not getting errors anymore

#

but

#

its not following my player anymore

buoyant zenith
#

ok the if statement works now however the points value is not changing

harsh bobcat
#

also, if youre at all worried about v3 distance you can do

Vector2 pos = new Vector2(transform.position.x, transform.position.y);
float dist = Vector2.Distance(pos, target)
if (dist < whatever...
#

points didnt increase by 1?

buoyant zenith
#

In the if statement I have

points = points + 1; 
score.text = points.ToString();

Basically I want the text to change up 1 number everytime a new obj is instantiated

eager mango
buoyant zenith
#

which it works for the first obj

#

but doesnt work again

harsh bobcat
#

hold on post full code

#

since your check should be set back to true

buoyant zenith
# harsh bobcat hold on post full code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class ProductMoving : MonoBehaviour
{
    private float speed = 0.2f;
    private Vector2 target;
    public GameObject thisPaper;
    public TMP_Text score;
    private GameObject newPaper;
    private bool count = false;
    private int points = 0;

    void Start()
    {
        target = new Vector2(-0.542f, -0.33f);
    }

    void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
        
        if (Vector3.Distance(transform.position, target) < 0.1f && count.Equals(false))
        {
            count = true;
            points = points + 1;
            score.text = points.ToString();
            newPaper = Instantiate(thisPaper);
            newPaper.transform.position = new Vector2(0.007f, -0.042f);
        }

    }

}
#

it is very scuffed as i put it together at 2AM 😆

#

ohh its the count aint it

eager mango
#

thank youuu

#

got it i used [SerializeField]

#

so thats what its for

buoyant zenith
harsh bobcat
buoyant zenith
#

i want to add +1 to point as soon as a obj hits target

eager mango
#

is it the most preferred than the other methods?

harsh bobcat
worn stirrup
#

Is there any way to call "remove" on a slot that you destroyed the object from in a list?

#

Since normally you remove with the gameobject, how can I remove its index?

buoyant zenith
patent cradle
worn stirrup
#

oooo danke

harsh bobcat
worn stirrup
#

Okay so I thought I was having a different issue but after reading a bit I'm still confused about how to deal with this error:

buoyant zenith
harsh bobcat
#

wait @buoyant zenith what i said is completely wrong

#

so its that points for every item starts 0

#

you add one and then set text

#

make points static like public static int points so that every object shares that variable

eager mango
buoyant zenith
#

Thank you i forgot about that.

#

Thanks it works now.

harsh bobcat
#

nice glad to hear it

buoyant zenith
worn stirrup
#

I have a list trashinPlay that exists on a ScriptableObject that I add the scene's objects to when they spawn, however I want to currently delete all the saved objects from all the scriptableObject files, and when I try to loop through and delete all the TrashObjects within the trashInPlay variable on the ScriptableObject, I keep getting an error that the list doesn't exist?

#

I'm running it in OnDestroy, which is what I kept asking would run and still have access to the scene during exit, which it is supposed to

#
private void OnDestroy()
        {
            for (int i = 0; i < trashTypes.Count; i++)
            {
                for (int j = 0; j < trashTypes[i].trashInPlay.Count; j++)
                {
                    if (trashTypes[i].trashInPlay[i].gameObject != null)
                    {
                        Destroy(trashTypes[i].trashInPlay[j].gameObject);
                    }

                    trashTypes[i].trashInPlay.RemoveAt(j);
                }
            }
        }```
fervent furnace
#

trashTypes[i].trashInPlay[j].gameObject != null

#

try this first

patent cradle
worn stirrup
#

oh

#

i i

#

lmao

#

how the hyuck

leaden ice
#

Yeah that's also an issue - removing things from the list while iterating over it is going to cause issues

worn stirrup
#

let me see if that's i

fervent furnace
#

i remember RemoveAt(idx) will move all elements after idx forwards so that shouldnt be issue
but you may miss to destroy some elements

#

you need to iterate backward

leaden ice
#

it will definitely be an issue yes, you will miss things

modern creek
#

I have a game with some UI layer stuff and some world stuff. If I want to capture input in UI, I've traditionally done it by overriding the interfaces IPointerDownHandler, IPointerUpHandler, etc. I'm not familiar with how best to do this in world space so that it doesn't conflict with the UI layer captures. Lots of googling shows that people use Update() checking. Is there a better way?

viral igloo
#

Should I be posting my TTF font material question in dots or here?

half cloak
#

Hello all. Any method to execute Update method when my iPhone or Android turn to background mode?

swift falcon
half cloak
#

Update Method has stopped

swift falcon
#

maybe there is some option to it in build settings?

#

just my guess

half cloak
swift falcon
gray mural
#

I have a GameObject that has both DDOL and LevelManager scripts.

public class DDOL : MonoBehaviour
{
    private void Awake()
    {
        if (GameObject.FindGameObjectsWithTag("ScriptsHolder").Length > 1)
            Destroy(gameObject);
        else
            DontDestroyOnLoad(gameObject);
    }
}

In LevelManager I assign an instance to the script in Awake.

private void Awake()
{
    instance = this;
    // ...
}

Because of Destroying my GameObject in DDOL script it throws me this error:

MissingReferenceException: The object of type 'LevelManager' has been destroyed but you are still trying to access it.

I am very poor in working with instances and ddols, is there any possible solution for this issue?

half cloak
swift falcon
half cloak
swift falcon
half cloak
swift falcon
#

that u could use, im not 100% tho

half cloak
half cloak
tepid mulch
#

So recently I found out about the "Root motion" command in the animator but when I enable it it messes up all my animations. I need to enable it because one of the problems I have been getting is being fixed by the use of root motion. There's an animation if I press the "W" button it plays a certain animation on the camera where it goes forward then turns left. With root animation on it does the animation but the camera just rotates and doesn't move its position unless I hold the "W" button. Even then when I let it off it snaps back into its previous location

swift falcon
patent cradle
gray mural
#

How can this error be thrown if my script is definitely in the scene?

MissingReferenceException: The object of type 'LevelManager' has been destroyed but you are still trying to access it.
leaden ice
#

you'd have to show code / explain what's going on if you want more help

#

also show the rest of the error message

gray mural
leaden ice
gray mural
leaden ice
#

nor explained which script is on which object

#

in which scene

#

we don't have enough information to help you

gray mural
leaden ice
#

which is what?

#

SHow the full error message and the full scripts

#

and explain which objects in which scenes have which scripts on them

#

Don't make this a game of hide and seek. Just show us the details

leaden ice
#

Ok so show the LevelManager script now

gray mural
leaden ice
#

and show where and how you set up whatever UI button is invoking this thing

gray mural
leaden ice
gray mural
leaden ice
#

that code doesn't match with the error you showed

#

The error says:
LevelManager.LoadSceneAndLevelData (System.String sceneName, System.String levelId) (at Assets/#Scripts/Managers/LevelManager.cs:155)
implying line 155 would be inside a function called LoadSceneAndLevelData

gray mural
leaden ice
#

but the script you just shared has line 155 in the GetAllLevelIds function

#

it means you changed the script since you got the error

#

please get the error and don't change the script between sharing the error message and the code

gray mural
#

you can be sure that no behaviour was changed

leaden ice
#

right but now I don't know where the error is happening

#

because I can't match line numbers in the error up to the script

gray mural
#

now everything matches

leaden ice
#

your problem is that you are doing this regardless of whether this particular LevelManager instance is going to survive or not

#

so:

  • you load a new scene
  • instance = this; runs on the new LevelManager in Awake
  • The DDOL script destroys the new LevelManager (and itself)
#

and now your instance variable is pointing at the destroyed LevelManager instead of the good one

gray mural
leaden ice
#

so>?

#

It doesn't matter if there's an instance

#

your instance variable is pointing at the destroyed one

gray mural
#

but how do I fix it then?

#

Even if I make it null, it won't change anything ?

leaden ice
#

FOllow established singleton patterns

leaden ice
gray mural
leaden ice
#

you tried to do this cute thing with having a single DDOL script manage all the singletons

#

it's backfiring on you

#

just do it the normal way

gray mural
#

oh, I was trying to find DDOL patterns

gray mural
leaden ice
#

Many of those implementations provide a simple base class to inherit from

#

and idk what you mean by implement your own logic

#

the patterns are there to be copied

gray mural
#

for every GameObject.

leaden ice
#

The singleton script itself will make it DDOL

gray mural
leaden ice
#

the separate DDOL script is not helpful\

#

foillow the established patterns that are all over the place

gray mural
#

looks like I have to stop overthinking

mossy shard
#

got a question:
why when i rotate around the z axis a 2d object while i move, the movement is jerky

#

like laggy

leaden ice
#

we can't help you without knowing more

mossy shard
mossy shard
# leaden ice we can't help you without knowing more

The movement code:

 horizontal = InputSystem.GetHorizontal();
        vertical = InputSystem.GetVertical();

         Vector3 direction = new Vector3(horizontal, vertical).normalized;

         rb.velocity = direction * speed;

The player rotating by the mouse cursor (looking at it):

 Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        Vector2 watchDirection = new Vector2(mousePos.x - transform.position.x, mousePos.y - transform.position.y).normalized;

        transform.up = Vector2.Lerp(transform.up, watchDirection, rotationSpeed * Time.deltaTime);
leaden ice
#

you showed the same code snippet twice?

mossy shard
#

IM dumb

mossy shard
leaden ice
mossy shard
#

why is that

leaden ice
#

because you're fighting against the Rigidbody

#

which wants to control the object's motion

mossy shard
#

oh shoot

#

urgh

#

i forgor now that i froze the Z rotation....

#

i think this is a problem, am i right

mossy shard
mossy shard
worn stirrup
#

Is there a way to tell child objects of a parent not to react with opposite force when you move the parent with AddForce()?

swift falcon
#

you can unparent them, and then parent again

somber nacelle
swift falcon
#

and not children

worn stirrup
#

Yeah, it's rigidbodies under rigidbodies, which I'm starting to see is just really screwing a lot of things up lol

#

In this video, going up and down moves the socket (the part between the bars and the arms), but moving up and down flings the arms with the "opposing force"

somber nacelle
swift falcon
#

you could try forcing their velocity to 0 right after u do the push though

worn stirrup
#

I've tried many versions of that and not been able to get it to work, and the velocity can't be 0 because they're supposed to be actively seeking the rotation of the red ones

swift falcon
#

velocity and angular velocity are 2 different things

worn stirrup
#

They have fixed joints though, how would modifying the velocity of something that's being flung by its joint to rotate going to affect that UnityChanThink

#

I can try it, I've just tried resetting velocity on other objects and it consistently wouldn't work lol

#

nah, doesn't work :p

#

I think I just like

#

Wait

#

can rb components be enabled and disabled at runtime?

swift falcon
#

yes

mossy shard
swift falcon
#

but if ur parent moves ur object will move with the parent thats the thing

#

so idk if anything except unparenting will work for you

#

you could try saving world position of each children and force them to stay there after the push

somber nacelle
sharp yew
#

How would I clamp these values on input? I'm running into an issue where the player's right stick (moves reticle) is clamped to the screen bounds but their input can keep updating and increasing in value.

Vector2 aim = playerInputActions.crosshair.aim.ReadValue<Vector2>();

leaden ice
leaden ice
delicate oracle
#

Hey, i have this function which translates the suspension of my bike front wheel perfectly - but if my bike rotates 90 degrees on any axis the front wheel is flying away

Maybe someone have a good idea? ❤️

        private void SuspensionVisualUpdate(Transform transform)
        {
            if (!Grounded())
            {
                _wheelFrontSuspension.localPosition = Vector3.Lerp(_wheelFrontSuspension.localPosition, _wheelFrontSuspensionStartLocal, 0.05f);
                _wheelBackAngle.localPosition = Vector3.Lerp(_wheelBackAngle.localPosition, _wheelBackAngleStartLocal, 0.05f);
                return;
            }

            _wheelColliders[1].GetWorldPose(out var posBack, out var _);
            _wheelBackAngle.position = posBack;
            _wheelColliders[0].GetWorldPose(out var posFront, out var _);
            var distance = posFront.y - _wheelFrontSuspension.position.y;

            _wheelFrontSuspension.Translate(new Vector3(0, distance, 0), Space.Self);
        }
sharp yew
# leaden ice you'd clamp the reticle position, not the input data

So I believe I've done that as the reticle doesn't move past the screen. But the reticle's position does take the player's input of the right stick into account. So the input thinks the reticle is off screen and to bring it back I have to hold it equal to the amount that I held it past screen just to get the reticle to move the opposite direction.

leaden ice
#

you'd have to show your code

sharp yew
#

Lines 55 and 57 are currently clamping the positions

leaden ice
#

which seems it can freely go off screen etc

#

what's the relationship between targetPosition and aimOffset

#

what are they used for

#

and why are they different variables?

swift falcon
sharp yew
#

Uh hrm. So I used to have these lines

    // Apply the aim offset to the local position
    targetPosition.x += aimOffset.x;
    targetPosition.y += aimOffset.y;
#

I'm using an object in the world which is where target position comes from. And I have a sprite (the reticle) on the GUI that follows the object

#

So there are some conversions happening

#

The aimOffset is the data from the player input, the delta time, and the speed. That gets applied to the target position and then I convert that to the desired position and move the target there

swift falcon
#

xGunRotation = Mathf.Clamp(xGunRotation, -90, 90); and then use that transform.localRotation = Quaternion.Euler(xGunRotation, 0f, 0f);

grim copper
swift falcon
#

its gonna make sure your rotation doesnt go above or below limits, and than use that value that is already for sure not going over or below limits whereever u want

sharp yew
#

I'm not rotating the character though

swift falcon
#

you are rotating something

grim copper
sharp yew
#

I'm not

#

I'm moving something left and right and up and down

#

think of it like a gallery shooter

swift falcon
#

oooh i though u had different issue my bad

sharp yew
#

like Duck Hunt

#

no worries, I appreciate the insight though

#

Clamping the aimOffset sounds right to me

#

I can try that

delicate oracle
sharp yew
rough sorrel
#

Hi. One question, is there a way to like reference a custom folder in the built game folder please? Like for example to be able to add 3D models externally or json files please

#

like get what's in that folder I mean

robust dome
#

@rough sorrelhttps://docs.unity3d.com/ScriptReference/AssetDatabase.html

#

take a look at this

rough sorrel
uncut path
#

how do i use this to do more than one thing with out making a function, or do i have to make a function if i want it to do more than one thing?
myInputActionsGet.Player.Interact.performed += ctx => Debug.Log("Do this"), Debug.Log("And Do this")

uncut path
#

oh coo you can

somber nacelle
#

yes, but it will probably be better to just use a method so you can also unsubscribe from the event

#

otherwise you have to store the lambda in a delegate field so that you can subscribe the delegate to the event and be able to unsubscribe it

uncut path
#

Oh shoo your right.
Whats a better way to

myInputActionsGet.Player.Interact.performed += ctx =>
{
    hit.transform.SetParent(spawnAndHoldPosition);
    hit.transform.position = spawnAndHoldPosition.position;
};

Is there a different way to use the player Input system?

somber nacelle
#

use a method instead of a lambda

#

that would allow you to unsubscribe like i said before

uncut path
#

every time i pick up i need to subscribe, when when put down i need to unsubscribe the input performed?

somber nacelle
#

well if that hit is a local variable, then absolutely

#

if it is a field, then you just need to subscribe one time instead of every time you pick up an object. and you'll only need to unsubscribe when you want to stop reacting to the event

uncut path
#

Dose that mean right after "pick up" += I can -= since its picked up I don't need to use it anymore until the next time I "pick up". or am I over micromanaging?

somber nacelle
#

this is still a programming channel, mate

dense rock
#

sorry man

#

oh i didnt see the ping lol im tired sry

sharp yew
#

The X axis clamping works perfectly fine

#

But here, the reticle can only traverse in the red box area for some reason

#

not the whole viewport

bitter saffron
#

Hello guys ! If I want to procedurally generate chuncks of a gridded map let's say, is it better if I use prefabs of a typical map square, or instead I use premade scenes, with the sub scene tech ?

west sparrow
#

That depends a lot on what the content of a grid is and the size of everything. It might be fine to cram it all in, lazy load it as prefabs, bring it in as asset Bundles, or additive scene load.

west sparrow
young sage
#

is there a way to find the gameobject with a specific script attached to it?

west sparrow
#

But subscribing and unsubscribing seems more likely to introduce bugs to me

#

FindObjectOfType or FindObjectsOfType just be aware it is not that performant

#

I.e. using it an Awake isn't so bad, but in an Update would be not ideal

west sparrow
#

And it'll show you only objects with that component on it.

hard viper
#

does the record keyword work properly in this version of unity's C#?

#

I tried a bit a while ago, to no avail, but idk if I was just doing it wrong

somber nacelle
hard viper
#

ty

leaden solstice
simple egret
#

Wonder what are the "caveats" they're talking about, I mean records are just compiler trickery and expanded into a class/struct that implements IEquatable and stuff. Maybe because of the yet other caveat of the init properties

somber nacelle
#

it's the init thing and unity's serialization not supporting them

leaden solstice
simple egret
#

Ah yeah it indeeds creates init-only properties when adding stuff in the primary constructor

#

They'll have to do it at some point™️ when switching to the core CLR anyway

somber nacelle
simple egret
#

Would be nice if they finally fixed the naming conventions (=> this.Transform.Forward) at the same time but that would break everyone's code lmao. Maybe design a code fixer like they did when they obsoleted [GameObject].collider and others in favor of GetComponent

leaden solstice
#

That sounds like never gonna happen

somber nacelle
#

agreed, someone suggested going through and updating the naming and removing all of the obsolete members from super old versions in the future of unity and .net forum thread, but they shot it down iirc

simple egret
#

Yeah it would be a huge task, basically going over all exposed types to rework them
Meh nothing a good search & replace with an elaborate regex can't do

leaden solstice
#

Think they would be too worried for backward compatibility

#

And breaking reflections, etc

simple egret
#

Oh yeah there's the C++ bindings too that would need some updates

#

But yes at least removing the things marked as obsolete since 10 years would be nice

somber nacelle
oblique spoke
#

For a brief moment we had it with Unity Tiny 😛

night harness
#

Whats a common way of running a visual lerp when you wanna start it from something outside of Update? Coroutine?

green radish
#

I managed to figure it out after trying to wrap my brain around it for over an hour, decided to make a method shortening the process that also makes it more intuitive, I just plug in a transform and a Vector2 and it returns a localized Vector2

spiral crest
#

trying to build for android, any idea on these daemon errors?

leaden solstice
rigid island
#

oh it says use --status to get details

plucky karma
#

You cannot use Script Debugging for Android. Weird things happen. You can use Autoconnect Profiler to identify keypoints that could be causing your game to lose performance.

spiral crest
spiral crest
#

i dont think so

plucky karma
plucky karma
#

The temp I'm referring to is the cache folder inside projects/library folder.

spiral crest
#

the erros seem to have changed slightly

#

but not much

spiral crest
plucky karma
# spiral crest

Have you tried including the symbols.zip? It's in this image here just enable it.

plucky karma
#

debug

spiral crest
#

ok

spiral crest
wanton edge
spiral crest
wanton edge
spiral crest
spiral crest
spiral crest
#

none that I am aware of

wanton edge
#

Kk, do you have everything set up with Android studio?

spiral crest
wanton edge
#

In order to build to Android everything needs to be set up with studio.

It's not difficult but too deep to explain over discord.

spiral crest
#

do you have any reccomended tutorials?

wanton edge
#

It's really not difficult, should take you 30 min.

spiral crest
#

also, i forgot to mention but I am not sure if openjdk is installed

#

i got it set up in in system variables but java -version only shows runtime

wanton edge
#

If I remember correctly the install should handle all envs.

#

You just install through android studio.

#

I wouldn't reccomend the non studio way for a beginner.

spiral crest
#

the manual said i had to install jdk

wanton edge
#

That's handled in both unity hub and Android studio.

#

I'm 90% sure.

#

Last time I have done it.

plucky karma
#

You can install JDK through Unity Hub, but I've heard problem installing it in the past regarding which version to install and make Unity work with it.

spiral crest
wanton edge
#

There should be a sdk and something else.

plucky karma
#

NDK

wanton edge
#

^

spiral crest
wanton edge
#

Both yes

spiral crest
#

uhhh ok

#

how do i install the ndk in studio?

wanton edge
#

Google.

spiral crest
#

ok

cosmic rain
#

I'd suggest reading and understanding the error first.

wind wren
#

how can i remove the text from the button

prime sinew
wind wren
#

cause im following breckeys tutorials on TD and idk how he removed the button text

modern creek
#

you can find the component that has the text on it and delete the text component (right click, remove component), or alternatively set the text to ""

#

"TextMeshPro - Text" is the component on this image that has text functionality

modern creek
#

then it's underneath it in the hierarchy - unfold "ShopTurretItem"

cosmic rain
#

This is really beginner level question and not even code related.

wind wren
#

ooohhh

sharp yew
#

Has anyone ran into an issue with the new Input System and having objects or players keep moving after the input is released/let go?

wind wren
cosmic rain
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/

cosmic rain
sharp yew
#

It seems like I never reset the amont of aim offset applied to the object

#

Would I do that by setting the aimOffset to 0 after I move the object?

spiral crest
#

this fixed it

sharp yew
spiral crest
#

for some reason running the game in the editor doesnt work, only building it does

#

but that is a separate issue

golden lichen
#

anyone know how to run asynchronous code? What I have here doesn't work—I get the error "BuildNavMeshAsync can only be called from the main thread."

    public async override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (GUILayout.Button("Generate Navmesh"))
        {
            NavMeshBuilder.ClearAllNavMeshes();
            await Task.Run(() => NavMeshBuilder.BuildNavMeshAsync());
            Debug.Log("Navmesh Successfully baked!");
        }
    }
shell scarab
#

I'm destroying a lot of gameobjects at once, but It doesn't seem to be destroying all of them? You can see in the deubg log:

Destroyed by Walk 12,1
which is called right after destroying it.

#
        for (int i = 0; i < maxSize.x; i++)
        {
            for (int j = 0; j < maxSize.y; j++)
            {
                if (rooms[i, j] != null && rooms[i, j].walkValue == 0)
                {
                    Object.Destroy(rooms[i, j]);
                    Debug.Log($"Destroyed By Walk: {rooms[i, j]}");
                }

                if (slow)
                    yield return null;
            }
        }
mossy snow
#

it doesn't look like BuildNavMeshAsync is awaitable though

golden lichen
#

async await is what I'm used to coming from Javascript

mossy snow
#

looks like you'll have to use NavMeshBuilder.isRunning

shell scarab
leaden solstice
#

You are deleting component not game object then

shell scarab
#

why does it work for the others then

#

because that whole space is covered in blue cubes at the start

leaden solstice
#

Idk, something else is deleting your GO

shell scarab
#

i mean the blue cube SHOULD dissapear

#

the blue cube is drawn with a gizmo via TestRoom

#

so just destroying TestRoom should destroy it

#

however I think i found the problem, i think it's actually adding duplicates somehow

leaden solstice
#

K then your array does not contain all of them or your condition is wrong

shell scarab
#

yea, I think it's somehow spawning multiple with only adding 1 to the array

thick terrace
golden lichen
#

thanks
I'm unfamiliar what Task.Yield() does though

cosmic rain
#

Might want to read through C# manual on async await(and potentially other things), since it's probably different from JavaScript.

And then through unity manual on "await support" as it is also a bit different from plain C#.

golden lichen
#

the only time I used async await in C# was Task.Delay(seconds)

thick terrace
#

specifically with unity's synchronization context, Task.Yield basically just delays one frame

golden lichen
cosmic rain
#

It probably is running on the main thread though. Just asynchronously.

Though there might be jobs involved as well.

thick terrace
golden lichen
#

I simply found it easier to read/implement than coroutines

#

though I didn't know there was a difference in performance

thick terrace
#

i don't think coroutines and async are drastically different in terms of performance but there's ways to shoot yourself in the foot either way, if you're doing something in a loop every frame you probably want to use the methods that don't allocate anything

scarlet kindle
#

Hey sorry I know this is a physics Q but no one ever replies in that thread.

I have weird coordinates for Z position on a prefab I put into my scene, and I don't understand why. All other objects have regular Z position of 0, but if I change the Z coordinate to anything other than this exponent then it disappears

cosmic rain
scarlet kindle
#

I will move it over there, thanks. I did change the child position of it to 0 0 0

#

but it was those coordinates originally

rancid frost
#

When unloading scenes, are static classes also destroyed?
Because it would appear so. And if so, how to stop being from being destroyed

leaden ice
rancid frost
leaden ice
#

So you're just talking about a component that you happen to have a static reference to

rancid frost
#

This class creates an audio source in the current scene and uses said audio source to play ui sounds

leaden ice
rancid frost
#

no no, thats not it

leaden ice
rancid frost
#

wait

#

I have 2 scenes,

Scene A and Scene B

I load Scene B,
When Scene B is fully loaded, it calls a method in said class which creates audio source and stores reference to it

when scene B is fully loaded, I then unload scene A

Scene A does not reference said static class or audio source in anyways

how ever when I unload it, the static class audio source reference becomes null....why?

leaden ice
rancid frost
#

the audio sources is still* active in scene B, said audio source is still there, but for some reason the static class lost reference to the audio source

leaden ice
#

How are you verifying:

  • that the object is created in scene B.
  • that the reference becomes null?
rancid frost
#

it is a method in SCENE B, that creates the audio source,

at no point does Scene A reference said audio source

leaden ice
rancid frost
leaden ice
rancid frost
leaden ice
#

sure but this doesn't really tell us that much

#

show the hierarchy before and after the audio obejct is created

#

show us where the object was created

#

and then show the hierarchy after scene a is unloaded

#

note that there are certain rules governing which scene a GameObject is created in when you run new GameObject (it's the "active scene", which has a very specific meaning).

leaden ice
#

The active scene can very easily not be the same scene that your script with the Start method there is part of

rancid frost
#

I see i see

#

but wouldnt that mean the adio source component will be destroyed?

leaden ice
#

I assume you're seeing some error or something

#

that you are trying to explain?

#

Mind sharing that error with the rest of us?

rancid frost
#

So this is the OBJECT before audio source

#

sec

#

audio source is still there

#

strangely, everything worked now...

#

the reference didnt turn to null

#

ima run again wtf

#

sigh

#

its working

#

wtf

#

i swear, 15 minutes a go, this shit wasnt working

#

wait, nvm, changed something 🙂

#

so the audio source is still there"

but the audio source reference is null

#

@leaden ice it only becomes null after the SCENE A gets unloaded,

#

Well, ive verified if the class is being reset and its not

#

so the reference is just being lost somehow...

rancid frost
whole mist
#

I want to make it so i can increase the kill count when an enemy dies, but if i did it through my enemyspawner it requires the prefab of the enemy. is there any way i can make it so i can access my controller without having to use it as a serializefield?

#

the one problem was that the controller was attached to the camera, a child of my player and it gets a type mismatch when i try to put it on the enemy prefab

lean sail
whole mist
#

is there a way to check onDestroy for a specific prefab?

lean sail
whole mist
#

i know that.

#

im asking like syntax

#

what is the way of writing it

rigid island
#

you could just pass the controller / counter script on instantiation of enemy

#

then increase when dead and destroy

lean sail
jagged snow
#

are you guys using Visual Studio Code?

steel finch
leaden ice
#

No, Rider.

whole mist
#

is there a way to check if an instantiated object has been destroyed?

jagged snow
leaden ice
#

(the "instantiated" bit is irrelevant)

whole mist
#

so in this case how would it be?

#

im generating a wave of enemy prefabs and want there to be both a wave limit and a limit to how many can spawn at once.

#

i just wanna check if one of the spawned enemies dies to reduce the remaining count

leaden ice
whole mist
#

yea

leaden ice
#

so put them in a list.

#
var newEnemy = Instantiate(enemyPrefab);
myEnemyList.Add(newEnemy);```
#

and then when you destroy the enemy:

if (health < 0) {
  EnemyManager.instance.ReportDeadEnemy(this.gameObject);
  Destroy(this.gameObject);
}```
something like that
#

and the ReportDeadEnemy function can remove it from the list

whole mist
#

is EnemyManager assuming that the name of my script is that?

leaden ice
#

yes

#

the name of the script that spawns enemies

#

and keeps a list of the enemies

#

also the .instance assumes that it's using a static instance reference

#

and that it's a singleton

whole mist
#

the instancing is a bit new to me how would i now reference it on the if (hp < 0) statement in my enemy script? i have it written like this in enemymanager

leaden ice
#

I'm confused as to what you're confused about I guess.

whole mist
#

well i just dont know how to define the instance fully i guess

#

cuz i dont know how to get the EnemyManager.instance part working

leaden ice
#

Well your public member there is Instance not instance

#

so you'd use that one naturally

whole mist
#

oops

#

lol

thin aurora
quartz folio
#

Though it should just be public static EnemySpawner Instance { get; private set; } with the backing field implicit.

glass plume
#

Hi, for some reason I am always getting the same random values

private void Randomize()
    {
        Random.InitState(System.DateTime.Now.Millisecond);
        rb.position = new Vector2(0, 0);

        while(startingDirection.x == 0 || startingDirection.y == 0)
        {
            startingDirection.x = Random.Range(-1f, 2f) * 10;
            startingDirection.y = Random.Range(-1f, 2f) * 10;
        }

        rb.velocity = startingDirection;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        
        if (collision.collider.name == "RightWall")
        {
            score.AddA();
            Randomize();
        }
        else if (collision.collider.name == "LeftWall")
        {
            score.AddB();
            Randomize();
        }
    }
#

Any ideas why?

dusk apex
ashen yoke
#

you init state every call

glass plume
#

I even tried changing the seed each time the method is called

glass plume
#

but not each time the Randomize method is called

dusk apex
#

Stop reseeding every call

glass plume
#

didnt work

dusk apex
#
void Awake()
{
    Random.InitState(System.DateTime.Now.Millisecond);
}
//...```
ashen yoke
#

then the problem is not in seed

#

run debugger over it

#

observe the values, something somewhere fails

glass plume
#
public class Ball : MonoBehaviour
{
    [SerializeField] private Vector2 startingDirection;
    [SerializeField] private GameObject gameManager;
    private Score score;
    private Rigidbody2D rb;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    void Start()
    {
        score = gameManager.GetComponent<Score>();

        rb.position = new Vector2(0, 0);
        Randomize();
        rb.velocity = startingDirection;
    }

    private void Randomize()
    {
        //Random.InitState(System.DateTime.Now.Millisecond);
        rb.position = new Vector2(0, 0);

        while(startingDirection.x == 0 || startingDirection.y == 0)
        {
            startingDirection.x = Random.Range(-1f, 2f) * 10;
            startingDirection.y = Random.Range(-1f, 2f) * 10;
        }

        rb.velocity = startingDirection;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        
        if (collision.collider.name == "RightWall")
        {
            score.AddA();
            Randomize();
        }
        else if (collision.collider.name == "LeftWall")
        {
            score.AddB();
            Randomize();
        }
    }
}

this is my entire code i dont know

#

I tried googling and the most I got was changing the seed

#

because when you search for non changing random value its people who dont know that the second max parameter doesnt include that number

dusk apex
glass plume
#

i mean my game runs I get no errors all good but

#

each time it "resets" the ball keeps coming at the same direction

#

it goes in the same direction over and over and over despite me doing Randomize() after each collision

ashen yoke
#

first call to Randomize

#

what is the value of startingDirection

glass plume
#

it changes each time i run

ashen yoke
#

alright, so at which time during consequtive calls the while condition will be true?

glass plume
dusk apex
#

Define reset.

glass plume
#

divide by 10 its 0.5 and 0.149

ashen yoke
#

while(startingDirection.x == 0 || startingDirection.y == 0)

#

when is this line true?

glass plume
#

if one of them is 0

dusk apex
#

Likely hardly ever if he's comparing floats.

ashen yoke
#

and when is it 0?

glass plume
#

in case the random value gave it a 0

ashen yoke
#

which is never

dusk apex
#

It's 0 by default? What's the initial value of startingDirection?
This could always be false.

glass plume
#

no it just can be 0

glass plume
ashen yoke
#

yes statistically it can be

#

no, the loop wont even run

fervent furnace
#

only when one of the component is 0 then reassign

ashen yoke
#

first call you may have a 0,0 vector there

#

you get your random values

#

second call, since it retains the values from previous call

#

the vector is not 0, thus the loop never runs

dusk apex
dusk apex
glass plume
#

or

#

i can just do do while

ashen yoke
#

problem is not the while

dusk apex
#

We're in agreement overall, just pointing stuff out.

ashen yoke
#

problem is that you are reusing previous random values to generate a new random

glass plume
#

hi

#

it works

#
public class Ball : MonoBehaviour
{
    [SerializeField] private Vector2 startingDirection;
    [SerializeField] private GameObject gameManager;
    private Score score;
    private Rigidbody2D rb;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    void Start()
    {
        score = gameManager.GetComponent<Score>();
        startingDirection = new Vector2(0, 0);

        rb.position = new Vector2(0, 0);
        Randomize();
        rb.velocity = startingDirection;
    }

    private void Randomize()
    {
        //Random.InitState(System.DateTime.Now.Millisecond);
        rb.position = new Vector2(0, 0);

        do
        {
            startingDirection.x = Random.Range(-1f, 2f) * 10;
            startingDirection.y = Random.Range(-1f, 2f) * 10;
        }
        while (startingDirection.x == 0 || startingDirection.y == 0);

        rb.velocity = startingDirection;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        
        if (collision.collider.name == "RightWall")
        {
            score.AddA();
            Randomize();
        }
        else if (collision.collider.name == "LeftWall")
        {
            score.AddB();
            Randomize();
        }
    }
}

i added a do to the while so it will run for one time no matter what

dusk apex
#

    private void Randomize()
    {
        //Random.InitState(System.DateTime.Now.Millisecond);
        rb.position = new Vector2(0, 0);
        Debug.Log($"Before Direction: {startingDirection}");
        while(startingDirection.x == 0 || startingDirection.y == 0)
        {
            startingDirection.x = Random.Range(-1f, 2f) * 10;
            startingDirection.y = Random.Range(-1f, 2f) * 10;
        }
        Debug.Log($"After Direction: {startingDirection}");
        rb.velocity = startingDirection;
    }```
glass plume
#

and i sort of initialized startingDirection in the start just out of tiny suspicion

#

it works now

ashen yoke
#

actually yes in this case you dont need the while loop

#

chance of actually hitting a 0 is astronomically low

glass plume
#

if its floating point 0 yes

#

like actual 0.0000000 yes

ashen yoke
#

also if its a direction vector you dont need to do that

#

just use Random.insideUnitCircle

glass plume
#

but if its 0.001 or anywhere in that range

ashen yoke
#

and clamp the vector magnitude to ensure min/max speed

glass plume
#

what if i just change the condition to x > -1 && x < 1

glass plume
#

regardless thanks for the assistance and help @ashen yoke @dusk apex

glass plume
#

returns a value between -1 and 1?

#

oh it returns a vector2 with a range i set

#

perfect

glass plume
#

why am I getting this error?

UnityEngine.Component.GetComponent[T] () (at <b41119cc6741409ea29f63c7f98de938>:0)
Menu.Awake () (at Assets/Menu.cs:16)```

```cs
public class Menu : MonoBehaviour
{
    [SerializeField] private Volume gv;
    private DepthOfField dof;
    private bool active = false;

    private void Awake()
    {
        dof = gv.GetComponent<DepthOfField>();
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Time.timeScale = active ? 1.0f : 0.0f;
            active = !active;
            dof.active = active;
        }
    }
}
dusk apex
#

GetComponent requires that the requested component 'DepthOfField' derives from MonoBehaviour or Component or is an interface.

#

Assuming you are not deriving from less common stuff.

glass plume
tender coral
glass plume
#

i just want to reference the DoF in the global volume and activate or deactivate it

tired elk
#

You need to use TryGetSettings on the volume ref I think, not GetComponent

ashen yoke
#

yes its not a component

glass plume
#

so DoF is not a component its a setting of volume?

dusk apex
glass plume
#

so i use TryGetComponenet on the Volume to retrieve ?

#

i mean i dont see other trygets

tired elk
glass plume
#

i am trying

dusk apex
#

Their example is with Fog

glass plume
#

oh ok yes i was starting to get the idea i was just writing the VolumeProfile

#
[SerializeField] private Volume gv;
    private VolumeProfile vp;
    private bool active = false;

    private void Awake()
    {
        vp = gv.sharedProfile;
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Time.timeScale = active ? 1.0f : 0.0f;
            active = !active;
            if(vp.TryGet<DepthOfField>(out var dof))
            {
                dof.active = active;
            }
        }
    }
#

why is it not working

#

same error

dusk apex
#

Did you save?

#

You couldn't be getting a get component error if not using the statement.

glass plume
#

after i saw error at line 16 (vp = gv.sharedProfile) referring to DoF

steel finch
glass plume
lucid wigeon
#

I have a Texture2D with tile atlas. I also know UVs of each tile. I'm using that on a terrain mesh, and assign UVs to the mesh. Now I want to have a UI Button for each tile with Image component (like an inventory) . How can I use this tile atlas (Texture2D) to assign the proper tile image to the Tile if I know the UVs?

olive sedge
#

Do you have to find the scene root in order to FindObjectsOfType

#

I'm Searching for a type I know exists and has the component available

#

But it returns zero results

#

What I'm trying to do is find each component of a certain type

leaden ice
#

Also make sure the objects You're looking for are ACTIVE

olive sedge
jovial moon
#

I am considering using longs instead of float or double to store xp.

#

Perhaps use 2 or 3 of the digits for an imaginary decimal place

#

Is it silly, or does it make sense?

#

It's a wide, lossless range of values...

leaden ice
jovial moon
#

Thank you!! 💕

#

I've been struggling so much deciding this!

olive sedge
#

OK so I've found that it was totally unecessary to call FindObjectsOfType since the class I was using was totally useless

#

Instead what I'm doing is storing a list of tags in the editor and using that

#

Faster and easier to understand

regal gyro
#

how can I make the int have a max value?
I'm trying to make an inventory system and trying to implement a max amount for each specific object

I've tried (value > 10) and (value == 10)

swift falcon
#

Mathf.Clamp() should work and so should the if statements?

regal gyro
swift falcon
#

Share code

#

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

regal gyro
#

hold on

tired elk
swift falcon
#

Common mistake^^ Ppl forget to set it as a return value

regal gyro
tired elk
#

The line just above

regal gyro
#

?

tired elk
swift falcon
#

How many does it say is in the inventory?

tired elk
#

Your problem is you don't clamp the actual value in your InventorySlot

swift falcon
#

Im confused by his code honestly

tired elk
#

Me too

regal gyro
swift falcon
#

When u add an item to the inventory theres an amount of "items" you add

#

Does the amount of items exceed ten?

regal gyro
#

it's related to other scriptableobjects

swift falcon
#

Ok so are you clamping the amount of inventory slots or items for one slot

regal gyro
#

items for one slot

swift falcon
#

Ok

#

So when you add items to a slot and the amount of items is over ten does it go over ten?

tired elk
#

What are you actually trying to do? Because you're looping through every slot, add amount in existing slot, clamp that value, then create a new slot. I don't understand your goal

swift falcon
#

Yeah i dont see why the slots arent premade and then you just add to them?

regal gyro
#

is that the flaw?

tired elk
#

I'm not even sure what your problem is at this point

swift falcon
#

No offense ofc

regal gyro
#

I am aware

tired elk
#

Yeah, it's just confusing

swift falcon
#

Its just a weird design. You should watch a tutorial

tired elk
#

What are you trying to achieve and what is your issue now ?

#

With more context than a simple clamp, we may be able to help

half cloak
#

Can I develop iOS app with writing native code even though I develop Unity app?

tired elk
regal gyro
tired elk
#

OK. Thanks for the clarification 🙂

half cloak
olive sedge
#

I have this object that searches through all the game objects in a scene to find ones that have tags that match a list.

#

Once it has this list, it applies a gravitational force to rigidbody2D components of gameobjects in the list.

#

But that introduces a problem

#

Once that object no longer exists in the scene tree, it still has a reference in the list and fills the log with errors

#

I want the gravitator object to remove objects from the list as they're destroyed without a strong coupling

#

My mind jumps to the observer pattern, but how it's implemented with UnityEvents is confusing

#

Do I really need a separate class for each event and instance of it happening?

#

That seems obtuse

swift falcon
#

Dependecy injection

olive sedge
#

The ideal solution would be to just have an event handler that's trying to look for a message being sent like

#

"Hey I'm destroyed. You can remove me from the list now."

swift falcon
#

If you know for a fact which gameobjects are going to use gravity why have something else manage them? Why not just let themselves manage it?

#

Why cant u just remove them from the list? Event -= Listener;

#

Oh Unity Events* if you want something like that youll prolly have to use C# events

#

I usually make a public static Action<>

olive sedge
#

The reason I'm having the gravitator class do the pulling is because the number of objects being affected by gravity is unlikely to exceed the number of objects doing the gravity

elfin tree
#

When instantiating a gameobject while defining it's parent transform. How can I place it to the top of the children hierarchy?

olive sedge
#

I want to be able to drop stars, planets, etc. in the scene with preconfigured tags and have them just...

#

Work

swift falcon
#

I getchu

olive sedge
#

If the things being pulled were applying the gravity, then each time a new gravity source is introduced I'd have to go through every single object affected by gravity and update their data

swift falcon
#

I would use C# events and just have them listen to it

olive sedge
#

I will look more into C# lists events

swift falcon
#

Its ez

#

Use Action<> and Func<> none of the outdated delegate bullshit

olive sedge
#

Here's the class by the way

tired elk
#

Action and Func are delegate you know ?

olive sedge
#

The problem is created when we generate the list of targets to apply gravity to

#

There's nothing in there to say

swift falcon
#

Peep how i said outdated***

olive sedge
#

"Oh, and when you're destroyed please let me know"

#

So it just hangs

swift falcon
#

Also if something is removing "itself" from a List<> i believe its supposed to do so backwards instead of forward

#

I forget the exact thing but its opposite from how its normally done

olive sedge
fervent furnace
#

i just remove at swap back.......

half cloak
#

Hey guys, Help please. I am currently developing app in Unity.

I complete to develop some features, but I have realized that there is no method like Update method which can be executed when the app is going to background mode.

So, I decide to separate those features to Two parts.

One can be executed on Unity.

The other can be only executed on iOS or Android.

In this case, I think I must develop both Unity and iOS & Android.

Can I develop both env ?? If it is possible, can you recommend some keyword for research for beginner like me??

If it is impossible, I remove this unity app and develop each mobile app (iOS, Android). What should I do? Thanks

prime sinew
prime sinew
#

Why is that in Update

hard viper
#

what is the name of the tool people use for benchmarking? Like, if I need to compare 2 operations 10,000 times? I usually see a common output for diagnostics

half cloak
fiery warren
#

How can I make the string include the variables ID & itemName, it won't work with $"{ID} - {itemName}" because it says I can't use
Error CS0236 A field initializer cannot reference the non-static field, method, or property 'BaseItem.ID' and I can't use just public static int ID because ID is used in another script and then that script won't work.

[System.Serializable]
public class BaseItem
{
   [SerializeField, HideInInspector] private new string elementName = "ID - Item Name";
   public int ID;
   public string itemName;
}
prime sinew
fiery warren
#
public class ItemManager : MonoBehaviour
{
    public ItemDatabase itemDataBase;

    public BaseItem GetItemByID(int id)
    {
        return itemDataBase.items.Find(item => item.ID == id);
    }
}```

```cs
public class GameManager : MonoBehaviour
{
    public ItemManager itemManager;

    public void UseItemByID(int id)
    {
        BaseItem item = itemManager.GetItemByID(id);
        if (item != null)
        {
            item.UseItem();
        }
    }
}```

```cs
[CreateAssetMenu(fileName = "New Item Database", menuName = "New Database/Item Database")]
public class ItemDatabase : ScriptableObject
{
    public List<BaseItem> items = new List<BaseItem>();
}```
dusk apex
#

||Reference the instance||

fiery warren
#

These are all the scripts working with that script

half cloak
prime sinew
#

and what Dalphat says is what you need to do. reference the variable, not the class name

prime sinew
#

does it need to be a variable? why not just override ToString

whole mist
#

im trying to get my EnemySpawner to correctly instantiate enemies from the enemiesToSpawn list and it isnt spawning any. is there anything wrong with the way i did this?

#

i keep getting index out of bounds errors everytime at the var newEnemy line, so my if isnt checking if the list is null properly

#

ive tried a bunch of different ways and none worked

gray mural
#

Is it possible to modify the size of the custom cursor?

lime patrol
#

Hello guys. I'm making 2D game and using Sprite Renderer for that ofc. Problem is it's not showing same on different devices. As you know Sprite no has Rect, Anchor feature.

How can i fix that problem? Should i convert all of them to Canvas Image? Thanks.

gray mural
fervent furnace
#

dont cross post, and i think you may include some example to demonstrate "not showing the same on different devices" (ie change the ratio)
if your game is ui-based (?) like card game or chess game then you may have to change it to ui element and use anchor to adjust

lime patrol
gray mural
lime patrol
gray mural
#

sprites don't have "different device feature"

#

so yes, you can use a script to convert them to UI

#

or manually

lime patrol
# gray mural sprites don't have "different device feature"

Reading Time: 11 minutes When creating a mobile game the hardest part is to make your game look the same on all screen sizes. In this post we are going to learn one neat trick that will help you make your game look the same on all mobile screen sizes

sharp yew
#

Is there a way to detect objects based on a radial offset of a raycast?

gray mural
sharp yew
#

I.E. give a raycast a sphere of detection around it

lime patrol
gray mural
#

you can also do that

sharp yew
#

ooo okay! I'll look into that

lime patrol
gray mural
lime patrol
#

What you suggest should i manually convert them to UI? So i can set them anchors.

gray mural
#

you can use a simple script to convert them

lime patrol
#

But should i change all anchors them?

gray mural
swift falcon
#

I wouldnt change them like that

lime patrol
#

Like that.

swift falcon
#

If your trying to change a gameobject to something UI...thru script

#

That just feels....wrong

gray mural
#

if they don't act as a npcs or players in their game

swift falcon
#

Just doesnt seem right? It should be one or the other

#

Thats just my opinion tho

gray mural
lime patrol
#

Convert this to

gray mural
lime patrol
#

Oh yes so many objects have animations..

gray mural
#

you'd better used the link you have sent to make a constant resolution

lime patrol
#

Here is result if i use that. Look that animal's placeholders...

#

I didn't set them in editor. Position was okay in editor.

gray mural
#

this way doesn't seem moveable

#

so you don't scroll it

#

that's why no reason to use different resolutions

#

just full window

lime patrol
#

Here is gameplay for you.

gray mural
#

the image you have sent is 1196x670
you can use that as your resolution

lime patrol
gray mural
#

nice game

lime patrol
#

I was made 2D game but didn't have this problem before. I really don't know what is the problem..

lime patrol
#

Gamebackground have gap on some mobile devices. Because they have bigger screen than i'm working on. I'm working on 2532 x 1170 pixels. Also on the video you can see i have circle shapes on right side. They not showing on smaller devices, i mean half of them are showing.

#

For background gap problem i wrote this. It solves it but the other problems...

tired elk
lime patrol
#

I used for "You Won" screen. It have Text and Button UI object.

tired elk
#

Yes, but the circle on the right side is ui too

#

it's shouldn't be anything else than ui

lime patrol
#

Hmm

tired elk
#

It's not a question of being playable or not

gray mural
#

have you ever seen a game with black background on the borders?

lime patrol
#

No ever because they are solving that problem somehow

tired elk
#

From my POV, you're game is a giant UI with draggable element and VFX/Animations to add some juice

gray mural
#

you can use something like this

tired elk
#

If you want it to be responsive, use UI

gray mural
#

you can see that resolutions are different

#

so the balls on the phone don't even look like a circle

#

so yes, lot's of games use black background

#

found in the internet

lime patrol
lime patrol
tired elk
#

Using UI image ._.

#

Instead of sprites renderer

lime patrol
tired elk
#

That you can use the anchors

gray mural
#

so that it will fit for all devices

tired elk
gray mural
tired elk
#

You did this as UI, right ?

gray mural
#

an image

lime patrol
#

No i didn't they are sprite renderer too.

tired elk
#

This part should be UI

gray mural
#

so it will look different on different devices with no black bg

lime patrol
#

So to summarize. If i use bigger background image for gap problem and for right side placeholders i should use UI?

tired elk
#

it's not animated, it's an interface the player can interact with and it should be place responsively in the overlay

lime patrol
#

Canvas should be Constanst Pixel Size?

#

Or should i make it Scale with screen size again?

#

It's last question. Sorry for taking time..

tired elk
lucid wigeon
#

Can generics be used in any way in Unity? Case: I have a generic PoolController script to pool instances of objects. List<GameObject> itemsInPool worked fine up to now. I'm in a need to use a interface PooleableItem<T>{ void Init(T params)} function for this to reset some common properties. I know interfaces cannot be serialized so perhaps I can use abstract class for that. But then those items cannot be serialized, I don't know if I'm not overcomplicating this.

hard viper
#

you can use generics just fine

leaden ice
hard viper
#

you just can't put generics into unity inspector

#

like as a monobehaviour

lucid wigeon
leaden ice
#

Interfaces and generics don't really have anything to do with each other

hard viper
#

specifically, if you have a Generic monobehaviour, that will work fine in C#. But you can't add a generic monobehaviour as a component

leaden ice
#

concrete genericized types can certainly be serialized

#

For example, you can serialize a List<int>

hard viper
#

you only really run into issues with inspector. As Unity won't display many types by default. ie Dictionaries. You need something special to serialize them.

#

And you can still do it. It just doesn't come out of the box

leaden ice
#

Let me put it this way. There's no such thing as a class that has a "List<T>" field. It will always be a field of some specific conrete type such as List<int>. Same goes if you have like an ObjectPool<T>. You would have an ObjectPool<Enemy> in any real implementation

#

now whether that thing is serializable or not is a different story but it wouldn't be specifically because of the generics

lucid wigeon
#

But I can't do something like this, right?

{
    [SerializeField] PooleableItem<T> itemsInPool;```
leaden ice
#

but in general no

hard viper
#

if you write that monobehavior like that, you can't even add it as a component

leaden ice
#

you can do this though:

public class EnemyPoolController : MonoBehaviour
{
    [SerializeField] PooleableItem<Monster> monsterPool;```
hard viper
#

so the SerializeField poolableitem doesn't even come into play

leaden ice
hard viper
#

at that point, don't you give it a concrete type?

#

ie not adding PoolController<T>, but PoolController<MyType>

leaden ice
#

well you can do cs public class MonsterPool : Pool<Monster>

leaden ice
#

it's PoolableItem<Monster>

lucid wigeon
#

I mean right now I have the code below, and I'm just thinking how if I can change it to still have just one PoolController script instead of creating new one for each type 😛 ```
public class PoolController : MonoBehaviour
{
[SerializeField] List<GameObject> itemsInPool;

lucid wigeon
lucid wigeon
hard viper
#

yes it is

#

if you want to add it to inspector and work with it

#

without adding extra things

ocean river
#

can i download the cinemachine from unity 2017.1 somewhere like github or archive.org?

#

like has anyone a link

#

i need it for 5.6

half cloak
#

Hello, Any Native audio plug-in Hello world example or articles??

valid vine
#

Idk where this fits so I'll put it here - I got these errors when I updated the unity version of my project and tried to build it

hexed coral
hexed coral
hexed coral
#

It's right next to Assets, in your project's root

hexed coral
valid vine
hexed coral
#

No

#

Library

valid vine
#

wait nvm

#

found it

hexed coral
#

It's not visible in the editor

#

Only on your file explorer

hard viper
#

what is a fast way to just count the number of bits set true in a long/int etc?

#

is there a way that does not involve looping

fervent furnace
#

impossible, change the implementation of your bit vector

hard viper
#

would it work if I worked in uint64 instead?

#

I tried to use BitOperations, but I don't think I have that namespace in unity. And I heard about CLS compliance being an issue

valid vine
hard viper
#

just to give a full picture, I'm trying to use a long as a way to hold 64 booleans, where I can do bitwise math etc.

naive swallow
#

I have a component that is added at runtime via AddComponent and I need it to have a reference to a Material. Is there a better way to have a script that never touches the inspector outside of play mode have a reference to an asset than using Resources? I have managed to avoid using Resources this far and it'd be annoying to use it for this one material

hard viper
#

I would like to know before I go too deep if I should do what I'm doing as long, vs Uint64, vs something else that will make my life easier

#

I'm going through a painful refactor right now, and want to avoid making it even more painful lol

kind pine
#

finally had a good excuse to use WolframAlpha.com I figured f(x) = ((x (1 - sqrt(1 - z^2)))/sqrt(1 - z^2) + x)^2 but needed it simplified... Wolfram knocked it down to f(x) = x^2/(1 - z^2)☀️ 💩

fervent furnace
#

O(1) algorithm for long... id even understand how they comes up with this algorithm....

leaden solstice
warm bronze
#

Would anyone be willing to help me make a unity script to make interacting with my api easier?

#

Please ping me/dm me if you do.

naive swallow
#

Just wish you could use those editor-defined defaults at runtime

uncut path
#

_ _
C = collider
R = Renderer

I'm not sure how to ask this.
I want to get the render when recast hovers over collider even when the render isnt on the collider but a parent or child.
Debug.Log(hit.collider.GetComponent<Renderer>().material.name);

leaden ice
simple egret
#

(despite its name, GetComponentInParent also searches that object before going up, so it works even if you hit the topmost object)

leaden ice
# uncut path

in this case I would honestly put a component on the ElectricWire variant object. Let's call it Wire for example. Wire can have a reference to its renderer. So you can do this:

Wire wire = hit.collider.GetComponentInParent<Wire>();
if (wire != null) {
  wire.ShowElectricShock(); // or whatever you're trying to do. In this function you would manipulate the renderer as desired.
}```
#

this way will work even when it's a sibling of the parent(s) of the collider, since the Wire is the root of the hierarchy

steady moat
leaden ice
#

it also lets you manage when this interaction with the wire conflicts with or interacts with other wire interactions etc in a central place

uncut path
#

I'm making a pick up script and i want anything in a pickup layer to glow when hover the pickup collider.

simple egret
#

Yeah so attach a script and search for that instead. That way you have room for improvement, say when you want to display the glow in a different color, or some custom text

leaden ice
#

and use GetComponentInParent<SelectionGlow>() and call StartGlowing() / StopGlowing() on it as necessary

uncut path
#

dose that mean I'm going to have to put a script on the collider that references the wire renderer

//put this on the colidder object child obj
public Renderer ren;
leaden ice
#

on the root object of the selectable/glowy thing

uncut path
#

I am unable to GetConponent<rootObject> from the child collider

leaden ice
#

What does that even mean?

#

GetComponentInParent<SelectionGlow>() as mentioned already

uncut path
#

i dont know how to get the root object from the child

leaden ice
#

I just showed you

uncut path
#

then why want i able to GetComponentInParent<Renderer>() rootObject.

leaden ice
#

Have you not been reading anything I've been writing?

uncut path
#

ill make a selection script that gose on the parent obj that the makes parent render materal glow.

leaden ice
#

yes, you should already have that if you are going to be making selectable things

#

Basically - the glowing renderer thing is at least one step removed from the script that actually does raycasting

#

that should indeed be a script that just deals with a "selectable" component

#

the selectable component can handle the glowing bit

hard quiver
#

The gameobject (player) moves in x-axis when pressing "w"

#

the rotation works fine

#

but it goes horizontal instead of vertical

#

also no backwards movement

simple egret
#

Line 38 is not correct, you should be using transform.forward if you want to go forwards with the vertical axis

#

Assuming the object's "forward" points correctly to the local Z axis

rigid island
#

Vector3.forward will give World regardless transform orientation @hard quiver

hard quiver
leaden ice
#

transform.up if you want it to move upwards

hard quiver
simple egret
#

Forwards is not upwards fyi

hard quiver
#

thx, i knew it was something stupid

simple egret
#

Upwards is Y, forwards is Z

hard quiver
#

well it does what i wanted it to do

#

maybe i should add its 2d

shell scarab
#

any way to improve this portion of my level gen that's determining the contiguous portion of the level? Basically freezes at large map sizes. TestRoom is just a class that contains some info ab the room like the walkValue and what connections it has. rooms[maxSize.x / 2, maxSize.y / 2] is guaranteed to exist.

// walk rooms
Queue<TestRoom> open = new();
open.Enqueue(rooms[maxSize.x / 2, maxSize.y / 2]);

int walkCount = 1;
bool init = false;
while (open.Count > 0)
{
  TestRoom working = open.Dequeue();
  working.ran = true;

  IEnumerable<TestRoom> gotRooms = GetNeighborsAdjacent((int)working.transform.position.x, (int)working.transform.position.z);
  int max = 0;
  int index = 0;
   foreach (TestRoom room in gotRooms)
   {
    if (room != null)
    {
      working.connections |= (Connections)(1 << index);
      if (room.walkValue > max)
        max = room.walkValue;
      if (room.walkValue == 0)
      {
        open.Enqueue(room);
        walkCount++;
      }
    }
    index++;
  }

  working.walkValue = init ? max + 1 : 1;
  init = true;

  if (slow)
    yield return null;
}
leaden ice
#

If that's not good enough you'll have to break it doen even further

shell scarab
#

but wouldn't that just slow it down technically, not actually make it faster?

leaden ice
#

yes it would help alleviate the "freezing"

#

you can use the profiler to see what the issue is with the speed

shell scarab
#

hold on, I actually noticed I forgot to include .Except(open) after GetNeighborsAdjacent, which returns an array of 4, up/down/left/right.

leaden ice
#

perhaps, for example, GetNeighborsAdjacent is allocating memory which can make this quite slow

shell scarab
#

ah it is allocating memory! I should reuse an array instead

leaden ice
#

to see what the bottleneck is

#

but yea it's likely reusing a List will be better

vivid wind
#

I feel like I'm missing something very basic. I'm trying out a tutorial for a basic field of view. Trying to do a 2D raycast for generating a vertex point. However, the raycast is returning a collider, but an empty point (0,0) for every raycast. Any ideas why the raycast wouldn't be returning a point? `float angle = 0f;
float angleIncrease = FoV / RayCount;
Vector3 origin = Vector3.zero;

    Vector3[] verticies = new Vector3[RayCount + 1 + 1];
    Vector2[] uv = new Vector2[verticies.Length];
    int[] triangles = new int[RayCount * 3];

    verticies[0] = origin;
    int vertIndex = 1;
    int triIndex = 0;
    for(int i = 0; i <= RayCount; i++)
    {
        Vector3 vertex;
        RaycastHit2D ray = Physics2D.Raycast(origin, GetVectorFromAngle(angle), ViewDistance);
        if (ray.collider == null)
        {
            vertex = origin + GetVectorFromAngle(angle) * ViewDistance;
        }
        else
        {
            vertex = ray.point;
        }
        verticies[vertIndex] = vertex;

        if (i > 0)
        {
            triangles[triIndex + 0] = 0;
            triangles[triIndex + 1] = vertIndex - 1;
            triangles[triIndex + 2] = vertIndex;
            triIndex += 3;
        }
        vertIndex++;
        angle -= angleIncrease;
    }`
shell scarab
leaden ice
simple egret
leaden ice
#

I usually use a HashSet<TestRoom> to track which rooms have been visited already

vivid wind
simple egret
leaden ice
leaden ice
gray mural
#

Do buttons save their listeners when the same scene is loaded second time?
No, they don't, so listeners have to be added once more, right?