#💻┃code-beginner

1 messages · Page 134 of 1

oblique ginkgo
#

what do you mean by spinning to the right
like is it offcenter

vernal minnow
#

It's offcenter

short hazel
#

It's centered according to the object. You'd like to rotate it around the red cross here?

#

The red cross is off-center

vernal minnow
wintry dew
#

Hello guys how do i import packages like Quaternion because it seems like my code aren't compiling

oblique ginkgo
vernal minnow
#

So how do I adjust the cross location?

oblique ginkgo
#

then just move the sprite image

#

so its centred around where you want to rotate it

wintry dew
hidden sleet
#

anyone know of any kind of guide that shows off making a mobile input joystick without the new system? Just tried to implement it but it wasn't working out right, but I can't find any that cover the old input system

vernal minnow
#

So I need a new game object?

eternal falconBOT
wintry dew
#

Do these automagically obtain packages?

short hazel
#

The packages are there

oblique ginkgo
#

then just move the image

#

and delete the spriterenderer off the logic object

short hazel
#

Once that is done, it should be fixed

wintry dew
#

Oh i see

oblique ginkgo
#

and to fix the inverted rotation transform.eulerAngles = new(0f, 0f, transform.eulerAngles.z - (Input.GetAxis("Horizontal") * speed2 * Time.deltaTime * -10));

#

why does unity make clockwise rotation decreasing angle

wintry dew
#

Weird

queen adder
#

how to rotate an object around the origin, as in co ordinates (0, 0, 0)?

vernal minnow
#

Jeez, it's still doing the same lmao

oblique ginkgo
queen adder
#

ah ok

queen adder
#

thanks

oblique ginkgo
toxic latch
#

If you have a GameObject with a bool value of false, how do you set to true by simply adding an additional component? I can't seem to get it to work and I'm sure it's extremely simple.

short hazel
vernal minnow
oblique ginkgo
oblique ginkgo
toxic latch
#

via a script containing several variables attached to that object

oblique ginkgo
#

so a script with a bool value

#

uh theres probably an event for that

#

there is not, infact, an event for that
is there a reason you cant just getcomponent into your container and set the value?

vernal minnow
#

had to move the object which seems kinda odd

oblique ginkgo
#

why you got a circle

vernal minnow
#

thats the new hidden object

oblique ginkgo
#

so thats your logic one

#

youve got the image one as a child

toxic latch
vernal minnow
#

yeah, what i dont understand is why i had to move it to get the proper rotation

oblique ginkgo
vernal minnow
#

So is my code having an error or is this a common thing?

oblique ginkgo
oblique ginkgo
#

if you fix it somewhere its either in editor or in photoshop

#

this is fixing it in editor

vernal minnow
#

Alr, it just seems weird that the circle wouldn't go on the sprites center

#

Er wait, wouldn't go in the spot where the rotation should occur

short hazel
#

That's why you put the sprite as the child of an object, and offset the child so the desired point is at the center of the parent

#

Then rotate the parent

vernal minnow
#

Thanks for the help though

vernal minnow
#

Or no?

short hazel
#

Maybe? Your screenshots don't show the Transform arrows of the parent object, so can't say

vernal minnow
#

that better?

short hazel
#

Yep looks good, if you want it to rotate around that white circle

twin bison
#

Hi, I'm creating a very basic brick breaker clone. I have just implemented a little powerup system.
It works but I basically want some feedback on my solution and if I overcomplicated things.

So I have this base abstract class:

public abstract class Powerup : MonoBehaviour
{
    public float duration;
    protected Transform paddle;
    public abstract event Action PickedUp;

    public abstract IEnumerator OnPickup();
}

The only powerup I have a class that inherits this Powerup class - it has this event in it:

void OnCollisionEnter2D(Collision2D collisionInfo)
    {
        if (collisionInfo.gameObject.tag == "Player")
        {
            // Pickup stuff , make paddle wider etc.
            StartCoroutine(OnPickup());
            PickedUp?.Invoke();
        }
    }

The idea is to subscribe it in the game manager and add some score etc.

Is this a good way or how would you have done it? Am I overusing this observer pattern? Is a base class even necessarry? Other thoughts?

vernal minnow
#

it rotates around the guys head for some reason

#

which is intentional, but i dont understand the need for the offset

short hazel
#

Offset is there so you can, well, offset the center of rotation. Taking the center of the gray circle (a hat?) on your player, it would rotate like the red circle:

#

The center of the hat would stay along the red circle as you rotate. If that's not the case, the script that rotates is on the wrong object

atomic sierra
#

do you guys plan out your mini practice projects?

#

or do u just start coding random stuff trying to establish game mechanics

#

cuz i feel like every time i want to practice something, like player movement and ui, and continue to add on, i begin to require a plan so everything works together smoothly and nothing gets too convoluted

#

Is that just the case of practicing anything for game dev?

#

I apologize for spam of quesitons

lavish roost
#

if you dont have that much experience it might make more sense to plan it out because otherwise it might get overcompicated

atomic sierra
#

wdym by that, just in general understanding the concept of writing clean code? (I thought that requires planning out the program too)

#

oh wait

#

structure is different than clean

#

i assumed they'd be similar

atomic sierra
#

just in general just plan your code out and then overtime you develop that habit?

#

ability?

#

skill? idk what youd call it

lavish roost
#

doing a bunch of different projects over the years, doesnt even have to be gamedev

atomic sierra
#

oh i c

#

well i havent done that

#

so ig i have to plan my stuff out

#

thats annoying 😦

lavish roost
#

youll begin to notice patterns that make sense to do when you face certain problems

atomic sierra
#

oh i see

#

thanks for your input

#

cuz i at first felt like i was going about it the wrong way

#

but i can see that it takes time

lavish roost
#

but if you are more of a beginner it makes more sense to plan it out so you avoid these overcomplications

lavish roost
spring skiff
#

Any idea why the camera is not rotating to the NPC?

    [SerializeField] private Transform _TransformPlayerCamera;
    [SerializeField] private Transform target_LucyHead; // The object whose rotation we want to match.
    private float speed = 3f;
    private void FixedUpdate()
    {
        if (LucyHadHitPlayer)
        {
            Vector3 direction = target_LucyHead.position - target_LucyHead.transform.position;
            Quaternion rotation = Quaternion.LookRotation(direction);
            _TransformPlayerCamera.transform.rotation = Quaternion.Lerp(_TransformPlayerCamera.transform.rotation, rotation, speed * Time.deltaTime);
        }
    }

The Camera from the player should rotate to the head of the NPC if LucyHadHitPlayer.
Its not working, but it does reach this if statement, I checked it earlier with a print.

vernal minnow
#

how can i detect collision setting a value if object 1 is on object 2 and a different value when the objects are no longer touching

wintry quarry
rich adder
#

where is the code question?

hidden sleet
#

well it's related to unity settings, where could I ask about that?

hidden sleet
#

aight yeah that looks to be a better place to ask

vernal minnow
wintry quarry
#

Well otherObject is not a good name for the collision variable, but if you're using 2D physics yes that's the correct method signature for OnCollisionEnter2D

vernal minnow
#

Collision2D otherObject isnt this just any object with a 2d rigidbody?

wintry quarry
#

it's an object that describes the whole collision

queen adder
#

is it possible to make a custom attribute that works like ContextMenu, but automatically adds a button?

queen adder
#

to execute it

wintry quarry
#

No I mean... where would it add the button?

#

to what menu or interface?

queen adder
#
    [Button("my method name")]
private void namethatdoesntmatter()
    {
        Debug.Log("Button Pressed!");
    }```
wintry quarry
vernal minnow
#

void OnCollisionEnter2D(Collision2D GameObject CirclePrefab) is this more apropriate?

sand shale
#

Im trying to find people that are doing projects i can help with/team up with, do you guys know of any good places or such to find that

eternal falconBOT
sand shale
queen adder
#

naughty attributes is cool 🥹

late burrow
#

how i change array size of array of custom type

#

copyto erroring

queen adder
#

arrays arent meant to be resized

late burrow
#

that why i make new one

queen adder
#

but if you insist, just make a new array

late burrow
#

but custom type messes up copying from one to another

slender nymph
#

how

late burrow
#

Error CS0121 The call is ambiguous between the following methods or properties: 'MemoryExtensions.CopyTo<T>(T[], Span<T>)' and 'MemoryExtensions.CopyTo<T>(T[], Memory<T>)

queen adder
#

please show what code you did as well

wintry quarry
slender nymph
#

shouldn't you be using Array.CopyTo? 🤔

queen adder
#

or if desperate, just loop

late burrow
slender nymph
#

and what does the error say

#

also why do you have a type called arraylist

late burrow
wintry quarry
slender nymph
#

probably have the wrong using directive or something

late burrow
#

ah that sounded almost same

unborn wasp
#

Where is problem?

IEnumerator PlayAnimation()
{
    if (monsterSprites == null || monsterSprites.Length == 0 || monsterImage == null)
    {
        yield break;
    }

    while (true)
    {
        if (monsterImage != null) // Sprawdzamy, czy obiekt Image nadal istnieje
        {
            currentFrame = (currentFrame + 1) % monsterSprites.Length;
            monsterImage.sprite = monsterSprites[currentFrame];
        }
        yield return new WaitForSeconds(0.1f);
    }
}
wintry quarry
polar acorn
unborn wasp
wintry quarry
#

no

#

I wrote you the line you need

#

You can write your own script

#

also in the future share code here like this: !code

eternal falconBOT
unborn wasp
#

i ahve this

north kiln
#

Configure your IDE

#

!vs

eternal falconBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

wintry quarry
edgy fox
#

is this a bad warning or a neutral waringnng?

late burrow
#

if its not made by you neutral

edgy fox
#

not made by me

eternal needle
edgy fox
#

just appeared

eternal needle
#

you can probably restart and it should go away

edgy fox
#

already did

vernal minnow
#

Alr, I got my bullet to recognize that it's colliding with other objects, but how to I have it check to see if it's colliding with a specific game object?

wintry quarry
#

You probably don't want to actually check for a specific object, just one that has a specific tag or component on it

vernal minnow
#

Alr, tag it is

edgy fox
#

is there a way to increase Debug.DrawRay's brightness/size

vernal minnow
#

I think I have some old code that checks tags

edgy fox
#

on high res monitors it is barely percievable

wintry quarry
#

brightness you can change by just picking a brighter color

#

it's always 1px wide afaik

uncut dune
vernal minnow
#

`` void OnCollisionEnter2D(Collision2D otherObject)
{
string otherTag = gameObject.tag;
if (otherTag.Equals("player"))
{
// if we have touched the npc
if (otherObject.gameObject.CompareTag("shopkeep"))
{
Debug.Log("Collision Detected");
// show collision in debog log and destroy colided object

        }
    }
}``
uncut dune
#

Wpuld be something like that

vernal minnow
uncut dune
#

So your bullet is not trigger right?

vernal minnow
#

not currently

uncut dune
#

If not thats all there is to it

#

If it is instead of OnCollisionEnter2D()

#

It needs to be OnTriggerEnter2D(Collider2D other)

vernal minnow
#

technically, this code is for player interaction with an npc

uncut dune
vernal minnow
#

sweet

#

and how to i detect the leaving?

queen adder
#

OnCollisionExit2D(Collision2D otherObject)

vernal minnow
#

er how do i use oncollisionexit ig

queen adder
#

Same way

vernal minnow
#

ill try it, thanks

obsidian needle
#

I'm very unfamiliar with unity and c#, but I'm trying to make a script that reads the last mouse location after a click. I don't think the script is doing anything though.

In the code here, I'm trying to change the color of a sphere (just so I can see things visually). The sphere is staying it's default color, so I can't if the script is running. I made sure to add it in the execution order.

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

P.S. The end is supposed to set the sphere back to it's original color, and just to make sure I know how to read mouse input.

Also thinking back (0,0) is probably one of the corners, but shouldn't a material change still happen?

obsidian needle
kindred pawn
#

im pretty new to all this stuff but, what difrence between the tutorial (light) and my code (dark) is causing unity to say "all complier errors have to be fixed before entering playmode"

wintry quarry
#

so checking positive or negative won't get you a quadrant

north kiln
eternal falconBOT
north kiln
#

Basic spelling mistakes should not be possible

wintry quarry
vernal minnow
#

well shoot, its not detecting them

#

``void OnCollisionEnter2D(Collision2D otherObject)
{
// if we have touched the npc
if (otherObject.gameObject.CompareTag("shopkeep"))
{
Debug.Log("Hi NPC");
// show collision in debog log and destroy colided object

        }
 
}``
#

did i mess something up?

#

oh wait duh...

north kiln
#

Check whether the collision occurs at all

vernal minnow
#

i didnt add the tag

north kiln
#

and please use 3 backticks and cs: ```cs to create a codeblock that's highlighted

vernal minnow
#

nope, still broke

vernal minnow
#

just removing tag checker?

north kiln
#

Log outside of the tag check

vernal minnow
#

they arent colliding it seems

vernal minnow
#

Imma review my code again...

rich adder
#

and check the graph on the page?

wraith mango
#
            GameObject num1select = clickedObjects[0];
            GameObject num2select = clickedObjects[1];
            RaycastHit2D up = Physics2D.Raycast(num1select.transform.position, Vector2.up, 3);
            RaycastHit2D down = Physics2D.Raycast(num1select.transform.position, Vector2.down,3);
            RaycastHit2D left = Physics2D.Raycast(num1select.transform.position, Vector2.left,3);
            RaycastHit2D right = Physics2D.Raycast(num1select.transform.position, Vector2.right,3);
            if(up.collider.transform.position == num2select.transform.position || right.collider.transform.position == num2select.transform.position || 
            down.collider.transform.position == num2select.transform.position || left.collider.transform.position == num2select.transform.position)
            {
                Debug.Log("Detected!");
            }

so my goal is to detect whether or not an object is right next to the selected object
num1select = the first selected object
num2select = the second
the objects are being grabbed fine, but the raycasts don't seem to be working

vernal minnow
#

Yes and yes lol

slender nymph
slender nymph
wraith mango
dense root
#

!code

eternal falconBOT
wraith mango
slender nymph
bleak vale
#

how can I make a function onexit with raycast? I know that I can make if it hits with just if hit.gameobject but can I make an exit with that?

slender nymph
#

print what was hit. stop making assumptions about what you think your code is doing

dense root
#

So I'm trying to use the Pen pressure from a Wacom to draw however it does not want to work as intended... here's a snippet of the code. Any thoughts as to a fix?
https://gdl.space/ujeyunozek.cs

slender nymph
wraith mango
dense root
#

I'm wondering how to utilize Pen.current.pressure.ReadValue() effectively so that it functions as a mouse Input.GetKeyDown(KeyCode.Mouse0)

wraith mango
#

or is what it is supposed to be doing

bleak vale
swift crag
#

store the object you hit in a GameObject field

#

check if the object you are hitting is different

#

that's about it

slender nymph
swift crag
#

the more time you spend explaining to us why you don't need to debug your code, the longer it's going to take for you to fix your problem

wraith mango
#

not colliders

#

raycasts

slender nymph
#

and is that object that was hit at the same position as whatever that other object you are comparing it to is?

wraith mango
#

yes

slender nymph
#

prove it

#

and keep in mind that your if statement only works if the first cast hits something

wraith mango
#

oh that's a problem

robust condor
#

I have a tilemap grid (3D) and now I have mostly 1x1 cubes placed on the grid, saved position in Dictionary. But imagine if I have an L shaped object that are 4 1x1 cubes. Is there a way to get what tiles that L shape is occupying? When I place the L I only check the tile I click and add to the Dict, but the other 3 tiles will still be "empty". Even if my collider check solves that problem I feel the Dict will be incomplete for other use cases.

obsidian needle
#

can I link the game object in the scene to a script without dragging it in assets and making it a prefab? I get a circle with a cross if I drag from hierarchy, but when I run it I think it unlinks from the prefab.

slender nymph
#

assets cannot reference scene objects

obsidian needle
#

should I be able to drag an object from hierarchy onto the first option ?

limpid cave
#

Simple question: How do I decide what asset is in the foreground respectively the background? in 2D

slender nymph
queen adder
#

the edit didnt really helped

obsidian needle
#

how can tell a script what object it's referencing then ?

slender nymph
queen adder
#

do you mean, "what objects uses a specific script?"

vernal minnow
summer stump
slender nymph
vernal minnow
#

nope

#

earlier i asked about rotating the character

limpid cave
#

asset may have been the wrong word. I am completely fresh to coding so my vocabulary = bad rn. I want to make a background in a 2d space. I dont know how to make one thing be in front of another. How do you put something in front of another?

vernal minnow
#

they had me move the code to a parent object

queen adder
vernal minnow
#

the player wasnt connecting bc it didnt have any code or even a reference

north kiln
slender nymph
vernal minnow
vestal adder
#

when my enemy is killed all the new ones i instantiate are on one health

vernal minnow
#

or can i just move the collider location?

slender nymph
vestal adder
#

thank

#

🦧 👍

#

what would static health be

slender nymph
#

it would have the static keyword on the variable declaration. you do not want that

vestal adder
#

i dont think that is it then

#

i am finding prefabs quite confusing

queen adder
#

!code

eternal falconBOT
slender nymph
queen adder
#

this is a script i put into a object containing a capsule

#

for some reason, when i read values on the WASD controls,

vestal adder
#

i think i am doing that yeah

queen adder
#

nothing is picked up

slender nymph
queen adder
#

WHOOPS!

#

thanks

#

how did i overlook that so hard UnityChanHuh

vernal minnow
#

Well I added a box collidor, and am not trusting the "fix"

#

Surrounded the player with the controllers collider

queen adder
#

also

#

why dont some positions line up ?

vernal minnow
#

I feel like this will cause issues later, but I also need to start the next step so is it a bad idea to leave a potential break for later if it works now?

queen adder
#

for instance, my object and camera are both at position 0 and they're not inside each other

#

nevermind!

vernal minnow
#

Why is the canvas and legacy text so large when I create it?

frail star
#

Hello , If I have a value between 0 and 100 , Like say health , how can I get to be 0 - 1? should I be using Mathf.InverseLerp?

cosmic dagger
cosmic dagger
frail star
eternal needle
cosmic dagger
vernal minnow
#

What's wrong with legacy actually?

#

Fixed size by linking to camera

cosmic dagger
#

legacy is just that, legacy (old). text mesh pro is the de-facto norm and should always be used . . .

vernal minnow
#

Wait so did I accidentally just make my game tiny?

cosmic dagger
#

what? no. the canvas is always huge in the editor. that is it . . .

dense root
#

!code

eternal falconBOT
vernal minnow
#

And ig fits the screen automatically

swift crag
#

it can also do lots of fun stuff, like links and rich text formatting

vernal minnow
#

I feel like that's not too necessary for an arcade game

#

Unless it can also make pixelated text? That would be cool

cosmic dagger
#

it doesn't have to be. fonts look better and you can do more with text mesh pro. it's the new default and should always be used, that's it . . .

vernal minnow
#

Is it not more complicated to use though? I don't honestly know the formatting to use it in code

#

Actually I take that bad

#

I have a reference of it in my last project, I'll just copy that

cosmic dagger
#

no, it's just a class like everything else in unity. works the same as legacy text but more options . . .

swift crag
#

TextMeshPro is trivial to use

#

you have already spent more effort trying to convince yourself you don't need to use it than it takes to just use it

swift crag
vernal minnow
swift crag
#

It shows up in the scene view at a size such that each pixel is one unit/meter

#

This isn't actually how it's going to render. The position of the camera relative to this canvas is irrelevant.

#

It's going to be rendered directly onto your screen (hence the "overlay" name)

#

I would suggest putting on 2D mode while working on your UI. That makes it easier to look at.

vernal minnow
#

Ah, that's interesting then

swift crag
#

Press F with the canvas selected to fit it into your screen

vernal minnow
#

My normal setup isn't accessible rn sadly

swift crag
#

so you can see it

vernal minnow
#

Oh

#

🤦‍♂️

swift crag
#

I tend to use "Scale With Screen Size" on the Canvas Scaler component

#

you'll find this next to the Canvas component

vernal minnow
#

Is it not the camera that causes the issue?

#

Alr, imma have a look at this

swift crag
#

The camera has nothing to do with overlay canvas rendering.

#

Just the resolution the game's being rendered at.

#

The default, Constant Pixel Size, just keeps everything at a constant size

#

Scale With Screen Size causes things to resize as your resolution changes

#

The other big thing you need to do is set up your anchors correctly.

#

suppose you want to put a piece of text in the top left corner

vernal minnow
#

So it will prevent issues like being unable to see parts of the game on smaller screens?

swift crag
#

A common error is to just add the text and then drag it over to the corner.

#

This means that you're putting it a fixed distance from the center of the screen.

#

If the aspect ratio changes, you'll wind up with the element going off the screen

vernal minnow
#

Oh, my text is generally supposed to stay where I put it, I only use health bars and scores with anchors

swift crag
#

(and depending on your Canvas Scaler settings, just changing resolution might send it off-screen)

#

Oh, my text is generally supposed to stay where I put it,

but that's the thing -- where does it "stay" relative to?

vernal minnow
#

Oof, that's not good

swift crag
#

If you leave the anchor on the default settings and want your text to be on a screen edge, you'll have a bad time

vernal minnow
#

Like I have a text that should only be viewed when the camera is moved closer to the object

swift crag
vernal minnow
#

No idea

swift crag
#

where you put UI elements at specific places in the world, instead of drawing them like a HUD?

vernal minnow
#

Oh, then yes

swift crag
#

Ah, okay. That's simpler.

#

Although, for text, you can just use a regular TextMeshPro component

#

there's no need to use a Canvas in World Space mode

vernal minnow
#

Yeah I still don't know how to implement textmesh

swift crag
vernal minnow
#

I'm still looking for my review code bc I never use it

#

I have one on screen

swift crag
#

That's UI text.

#

It is a child of a Canvas.

vernal minnow
#

Oh

#

So it moves

swift crag
#

UI text is a different component.

swift crag
#

This canvas is stuck in front of the camera.

#

so, yes, it's going to move around

vernal minnow
#

That linked to the canvas too

swift crag
#

If you want text to appear at a specific place in the world, delete the Canvas and create non-UI text

swift crag
# swift crag

you can use the GameObject menu to quickly create a new object with non-UI text on it

vernal minnow
#

Would I not need the canvas to have moving code aswell?

swift crag
#

"moving code"?

vernal minnow
#

Crap

swift crag
#

back up and explain what you're trying to accomplish

vernal minnow
#

Imma need a sec to reword lmao

swift crag
#

no code or unity-specific terms

#

just the gameplay feature you want

vernal minnow
#

Don't know why I even said code there

#

Ok, I'm using the canvas for text that is always on the screen, (health, score, enemies left, time in game)
I am currently trying to make a text box that stays above the box, that when my character touches the box, it says a question that I can answer with one of two inputs be it y or n, if the player moves away, the text goes away aswell

#

I have the collision detection already

swift crag
#

Okay, so non-UI text would make sense here. But it would also be fine to use UI text on your existing canvas. You'd just need to write code that moves the text to the correct spot.

vernal minnow
#

The text showing is the issue considering I'd usually use legacy and don't know the code to use for textmesh

swift crag
#

the code is basically identical

#

TMP_Text is the type to use for referencing TextMeshPro components

vernal minnow
#

public Text NPCtext; is legacy right?

swift crag
#

That is legacy text.

vernal minnow
#

so i just do this? public TMP_Text NPCtext;

vernal minnow
#

NPCtext.text=""; so how do i convert this?

swift crag
#

just try it!

#

this is valid; TextMeshProUGUI is UI text (and TextMeshPro is non-UI text)

#

TMP_Text covers both

vernal minnow
#

then what are the two code lines that reffer is putting?

swift crag
#

this is not valid

vernal minnow
#

ah

swift crag
#

it's text, not Text

#

$"Some text" is an example of string interpolation. It lets you include expressions in a string.

vernal minnow
#

whats the $ symbol for?

#

oh

swift crag
#
int dollars = 100;
string result = $"I have {dollars} dollars":
#

It's an alternative to using string.Format (or just using + to glue things together)

vernal minnow
#

i can see a few uses for that

swift crag
#
float number = 3.6345893468934f;
Debug.Log($"It's roughly {number:N2}");
#

this would log It's roughly 3.63

vernal minnow
#

now i dont remember that

#

looks like i need to review my old c# notes

swift crag
#

anyway, TMP_Text should just be a drop-in replacement for Text for common usecases

vernal minnow
#

yeesh, I say old but ive only been doing this for a year...

vernal minnow
#

alr, ill try it

swift crag
#

just try it!

#

you won't go to jail for making a syntax error

vernal minnow
#

crap, do i need a new using statement?

swift crag
#

yes

#

using TMPro;

#

your IDE should be able to suggest this

frail star
vernal minnow
#

was i supposed to configure the ide in someway? (Visual studios was installed by unity)

dense root
eternal falconBOT
swift crag
#

do this if you aren't getting error highlighting and suggestions

vernal minnow
#

well it kinda worked, the text is kinda blurry

swift crag
#

That's because your game view is scaled

#

now, I'm not entirely sure why that is..

#

try messing with the slider

vernal minnow
#

it only lets me make it bigger

eternal needle
vernal minnow
#

odd bc i dont recall messing with that and nothing was being blurred earlier...

queen adder
#

why is my rigid body dragging so hard when the drag is set to 0?

vernal minnow
#

but hey, the interaction works so thanks man

queen adder
#

im using rigidbody.addforce() to move my object continouisly

wintry quarry
queen adder
#

like this

queen adder
wintry quarry
#

then there's friction

queen adder
#

    public static int Hero = LayerMask.GetMask("Hero");
    public static int Monster = LayerMask.GetMask("Monster");
    public static int Tilemaps = LayerMask.GetMask("Tilemaps");
    public static int Buildings = LayerMask.GetMask("Buildings");
    public static int Anything = Hero | Monster | Tilemaps | Monster;
```why am i failing to hit Anything?
swift crag
wintry quarry
frail star
swift crag
#

"Low Resolution Aspect Ratios"

#

(it's fine if it's grayed out)

wintry quarry
#

wait also - not sure you can use GetMask in a static context like that. @queen adder

queen adder
swift crag
#

the console should have errors about using LayerMask like that

#

here's an alternative!

wintry quarry
queen adder
#

i love it when compsci people use "illegal" to refer to errors in code

swift crag
#
    public static int MyCoolLayer;

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    static void SetupLayers()
    {
        MyCoolLayer = LayerMask.GetMask("Cool");
    }
vernal minnow
queen adder
#

favroite word to use when talking about code

swift crag
eternal needle
queen adder
#

cool attribut

swift crag
#

i got errors when i tried to use GetMask to initialize a static field

#

now that did happen to be on a ScriptableObject that was getting loaded super early. then Unity crashed

#

let's try that again

frail star
swift crag
#

maybe it's OK if you do it in a plain old C# class?

queen adder
#

it's in a mb

swift crag
rich adder
#

maybe because using old unity?

swift crag
#

ah, true

queen adder
#

ok

swift crag
#

it could still be failing

queen adder
#

ive confirmed its nto friction

swift crag
#

verify that the values make sense

queen adder
#

i disabled the use gravity check

#

and while it was floating this problem persisted

swift crag
#

go figure.

queen adder
vernal minnow
#

how do you make an immovable object?

swift crag
#

if you put a Cube in your world, it will never move.

vernal minnow
#

my player just walks through the other on collision

swift crag
#

oh, you're asking how to stop the player from walking through things

vernal minnow
#

yes

cosmic dagger
swift crag
vernal minnow
#

i need to start being more clear with my questions...

#

            transform.eulerAngles = new(0f, 0f, transform.eulerAngles.z + (Input.GetAxis("Horizontal") * speed2 * Time.deltaTime * -10));//transform.Rotate(new Vector3(0, 0, Input.GetAxis("Horizontal") * speed2 * Time.deltaTime * -10));
queen adder
#

you need to detect things first

vernal minnow
#

it detects collision

queen adder
#

you'ld better use other system then, like physics

rich adder
vernal minnow
#

thats just my move code

queen adder
#

use physics to move physics things

swift crag
queen adder
#

try rigidbody

swift crag
#

it has no clue what's going in the world around it

queen adder
#

or charcontroller

rich adder
vernal minnow
swift crag
#

A rigidbody would be a good choice, yes. That will let your character interact with the physics world

vernal minnow
#

rigid body

cosmic dagger
rich adder
#

not Transform

queen adder
#

if you wanna make a player character move you choose to move it through a rigidbody's move method or a charcontrollers move method

#

or, if you insist using transform, do physics casts each time you try to move

#

if youre changing the position directly

#

thats kind of a huge no no

#

i mean i wouldnt know much but im pretty sure it could be tedious coding that way

frail star
rich adder
queen adder
#

how do i fix my character sliding like a penguin? i turnt the RB drag to 0 and its still sliding

rich adder
#

dirty xD

swift crag
queen adder
#

this isnt through friction however

swift crag
#

I didn't realize you could just use LayerMask.GetMask to initialize static fields on non-unity objects

#

so that's probably the best way to do it

queen adder
swift crag
#

I was doing it in RuntimeInitializeOnLoadMethod-tagged methods haha

#

If you want to have these static fields be on a MonoBehaviour, then you can use that

#

It's a super useful attribute. It lets you execute static methods at various points in the startup process

#

I use that to fire up my game controller, which loads a bunch of other stuff

eternal needle
queen adder
#

u2017 is a pog having no problems at static initializer on getmask though

swift crag
queen adder
#

ah that, the problem is the raycast was in wrong position UnityChanOops
But still, each of the ints here works fine even before the Anything was added

vernal minnow
#

so i can push objects, but cant use them as walls, thats irritating considering its how i stopped my character in my last game...

#

imma check my old code to see what stupidity i used to accomplish that

swift crag
#

most likely a rigidbody

vernal minnow
#

the code is the same

#

i may have found a fix though

north kiln
north kiln
#

(statics are initialized when they are accessed for the first time)

swift crag
#

They're initialized on first usage of the type, aren't they?

queen adder
#

how do i fix my rigidbody addforce sliding the player?

#

here is my code

#

(groundDrag is set to 0)

vernal minnow
#

ah, i didnt have my seccond square collider

rich adder
queen adder
#

no

#

i dont want drag

#

my player slides too much

rich adder
#

you said rb is sliding

queen adder
#

yeah

rich adder
#

you need drag

queen adder
#

i need drag?

#

wait what

rich adder
#

drag = no sliding..

queen adder
#

i thought drag makes the player move after there is no force

rich adder
#

wait sorry use the friction

queen adder
#

huh

rich adder
#

brain fart

eternal needle
# queen adder how do i fix my rigidbody addforce sliding the player?

addForce isnt doing it at all, you are simply giving it force and never slowing the player down by yourself.
Also, you dont need to mess with drag here. You can keep it and friction at 0 if you want then do something to provide countermovement when the player should be slowing down

queen adder
#

where is friction?

rich adder
#

you can apply a physics material

#

change friction at will if you want

vernal minnow
#

well crap

eternal needle
queen adder
#

ohh

vernal minnow
#

how do i link two objects so that they cant be separated?

rich adder
vernal minnow
queen adder
#

does this change the velocity of my object?

rich adder
#

it Adds Force

queen adder
#

or does it translate its position the amount of the given variable

#

for instance if i am to call addforce() once what would happen

silver tendon
#

possibly a very easy and dumb question:
how do i disable the editor from responding to the alt key when in play mode? trying to test using alt as an input and it opens the editor's menus/shortcuts

eternal needle
# queen adder negative addforce?

yea thats what i would do if I had to, although changing the velocity is a lot easier since you really dont need proper physics interactions most of the time

rich adder
#

the button with crossed out keyboard

queen adder
#

ok

queen adder
eternal needle
rich adder
queen adder
silver tendon
rich adder
queen adder
#

if you jump, you have to like disable your velocity manipulator

#

things like that

rich adder
#

yeah its a pain

eternal needle
silver tendon
queen adder
rich adder
#

something odd on your end

eternal needle
silver tendon
rich adder
silver tendon
queen adder
#
    public static int Buildings = LayerMask.GetMask("Buildings");
    public static int Anything => Hero | Monster | Tilemaps | Monster;
```omg... i know now the real problem...
#

I was testing to hit Building... it wasnt listed

#

actually, imma test as well if non prop works still

#

yea, can work without getter prop (dunno why though)

limpid cave
#

In 2D. I am trying to make 2 different objects appear at the same x level but the issue I have is that it seems that each object have their own x value. Am I mistaken?

#

Let me rephrase

#

Each object on the same horizontal line also have an independent x levels

cosmic dagger
#

the x axis is left-to-right. also, each object has their own position . . .

limpid cave
#

Tried to clear that up in the last sentance but it wasn't clear

queen adder
#

@swift crag how did you try to make static getmasks earlier

swift crag
#

I put static fields on a ScriptableObject, then a MonoBehaviour

queen adder
#

you put it in a mb that exists originally in the scene?

#

yea, that caused me hiccups too just now

limpid cave
queen adder
#

apprently, mb loads all of it's static when it have an instance

#

or... mb really just hates having static getmasks

#

actually, it explicitly said here 😁 not about the static, it's just about being in a field initializer

queen adder
#

Can someone help me with this code to make a camera rotate around a GameObject (Empty) it returns one error that says that I can't convert a transform to a quaternion https://pastecode.io/s/dzty46o2

cosmic dagger
queen adder
cosmic dagger
#

is the script you posted cameraCont? i see no code on line 18 . . .

queen adder
#

wait, it says it's for another script sorry

cosmic dagger
#

yep, thought so. always read the error messages . . .

queen adder
rich adder
eternal needle
queen adder
#

ok

rich adder
eternal falconBOT
dense root
#

!code

eternal falconBOT
dense root
#

So I'm trying to get my Wacom pen working with Unity, however it does not seem to want to input as intended... any thoughts?
https://gdl.space/giqajeqoqi.cs

near wadi
#

does Input.GetKeyUp still work with the new input system, or should i skip this part of this tutorial?

rich adder
#

only Input is set to Both

near wadi
#

Oh, cool. Ok, thanks

wintry quarry
near wadi
dense root
#

Anyone here have any idea as to how to implement a Wacom pen into unity? I've attached my script above but I'm totally stuck on how to get it going

obsidian needle
#

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

is there a good way to add a delay to this script? I'm trying to make a confirmation system that you have to click twice, but they happen instantaneously. I get a type error if I try to WaitUntil the mouse button comes up.

wintry quarry
dense root
#

Yeah I see that

robust condor
#

I have two prefabs, face and cube. On awake I want to instantiate 4 faces around a cube in all directions. But it is always instantiates in the direction of how the prefab was setup in editor. Even if I change localPosition to Vector3.zero, Vector3.right etc. Instantiate(randomface, gameObject.transform.localPosition = Vector3.left, Quaternion.identity, gameObject.transform); Also need to rotate the face so it faces outwards in all directions

timber tide
#

position != direction

#

and that you're setting the rotation always to the Quaternion identity

#

so there's not really anything changing from how it's set up in the editor

robust condor
#

Right I figured out Quaternion.Euler(0, 0, 180f);

#

Turns out I only need to change the euler

placid ice
#

singleton script is the script only or the whole object the script contains ?

gaunt ice
#

dont understand
singleton means there is only one instance of that class (script) is allowed in memory

grave sinew
#

need help with thing

#

so its saying that "Look" isnt defined under OnFoot actions but im pretty sure it is

#

i dunno whar do

robust condor
#

Code?

grave sinew
robust condor
#

You have no code?

#

Oh the white stuff

grave sinew
#

yes yes

robust condor
#

Kinda hard to read

grave sinew
#

yeah its just the shitty notebook app that came with whatever version of ubuntu this is

robust condor
#

Why do you have a . on OnFootActions

queen adder
#

the prefab is the wrong rotation when it spawns in it just lays flat on the ground

#

(wheel is a resized cylinder)

grave sinew
#

i wonder if thats it

#

maybe

keen dew
#

That's not it

#

Do you have "generate C# class" checked?

robust condor
#

You should config your IDE

#

!ide

eternal falconBOT
grave sinew
grave sinew
robust condor
#

You can bind actions using FindAction

#

pointerPosition = actionMap.FindAction("PointerPosition");

grave sinew
#

honestly i think im just gonna find some other code to run the mouseLook off of

#

everything else works fine

robust condor
#

Also onFoot.Look doesn't exist because it's not instantiated

#

You would see this if you had a proper IDE

keen dew
#

That's not how the input system works

robust condor
#

I can't even save in VS if I use PlayerInput.MyActionMap..

#

Oh you are generating C# classes

#

Yeah I don't use that

lean basin
#

Is there something like Start() and Awake() but called even if the gameObject is not active?
I found I could do ClassName() which they call constructor, but forum said I should not do that.

wintry quarry
#

What are you trying to do

#

If you just want to call a function, make a custom function and call it

lean basin
# wintry quarry What are you trying to do

I had a component for managing UI. I want this component to disable gameObject on start. This is for lazy idiot-proof and quick editing.

So I do Start() {gameObject.SetActive(false), but since Start() will be called when the object is activated, that mean if the gameObject is not active in the beginning, and then I activate it, it will call gameObject.SetActive(false). Which mean it won't be activated.

The problem is, sometimes the gameObject may be active and maybe not. If someone is making revision, it will be enabled. If they done they will disable it so it won't be dirtying up the editor.

wintry quarry
#

Leave that child deactivated

#

Let the parent (with the script) be active at all times

placid ice
gaunt ice
#

when you attach script to object, instance (component) of that script is created

wintry quarry
lone finch
#

How would you make a collision event when sprite leaves screen?

#

flappy bird clone btw

mild otter
#

Hi guys, can someone help me with this issue? when I put in the component it doesn't show all of it
Image

mild otter
#

there are no errors

keen dew
#

Then you know which link to click next

wintry quarry
#

BTW it doesn't look like your filename matches your class name

north kiln
wintry quarry
wintry quarry
north kiln
#

I never hammered down the specifics, as the only benefit would be to update my site 😛

mild otter
north kiln
#

It should be the same name as the class it contains

mild otter
wintry quarry
mild otter
wintry quarry
north kiln
#

They also misspelled that

#

it generally needs to be the same in both places

wintry quarry
keen dew
#

It should be the same as in the tutorial you're following

keen dew
#

I'm willing to bet money that there in fact are errors in the console

mild otter
keen dew
#

Yes, that's the problem

mild otter
#

Ok thanks a lot this was very helpful

mental wren
#

hi, i am running a unity3d game on linux and it is excruciatingly slow when loading scenes specifically. Everything else is fast. I built for Linux, tried Vulkan/default as the api.
Everything is fast except for scene loading which takes literally 3 to 4 minutes.

It's not even a big scene. It's the same for 4 character prefabs or 1 character prefab

GPU is Intel corporation device 46a8 (rev 0c), 16gb ram. How can i debug

wintry quarry
#

See what's actually taking up the time

desert current
#

Hello, I'm making a puzzle game, and wanted to add an "undo" feature, like the game Snakebird does, yet I am finding it hard to do so. I have managed to get one "undo" working, but as soon as I want to undo 2 moves, I have no idea what to do. Here is my current code.

gaunt ice
#

you need to know what is stack first

desert current
desert current
modest dust
#
Stack<Vector3> positions = new Stack<Vector3>();

...
positions.Push(pos1);
positions.Push(pos2);
positions.Push(pos3);

...
positions.Pop(); // returns pos3
positions.Pop(); // returns pos2
positions.Pop(); // returns pos1
modest dust
desert current
mental wren
twin bison
#

Hi, learning unity by creating a simple endless runner. I have now my first part done and thats the scrolling ground. What I don't get it that sometimes there is a weird gap between the "tiles" I spawn.

Here is the code:

void Start()
    {
        // Initially spawn a tile
        GameObject spawnedTile = Instantiate(GroundTile, Vector3.zero, Quaternion.identity);
        SpriteRenderer spriteR = GroundTile.GetComponent<SpriteRenderer>();
        _spriteWidth = spriteR.bounds.size.x;
        _activeTile = spawnedTile.transform;
        // spawn the second tile
        _nextTile = Instantiate(GroundTile, new Vector3(_spriteWidth, 0), Quaternion.identity).GetComponent<Transform>();
    }

    void Update()
    {
        if (_activeTile.transform.position.x <= -_spriteWidth)
        {

            // when the left most tile reaches the end spawn a new tile and switch active and next
            // sometgimes gap, why?
            _activeTile = _nextTile;
            _nextTile = Instantiate(GroundTile, new Vector3(_spriteWidth, 0), Quaternion.identity).GetComponent<Transform>();
            
        }
    }

The gap looks like this (see image)

I made it work with the workaround in the if statement in the update method doing this if(_activeTile.transform.position.x <= -_spriteWidth + 0.2f) -> But i really want to know why i have this problem in the first place. It's not logical to me

mental wren
#

ok stupid qn i found how to autoconnect profiler on build

modest dust
#

Spawn the new tile relative to the old one

#

new Vector3(oldTileXPos + 2 * spriteWidth, 0);

twin bison
modest dust
twin bison
#

But still not 100 % sure why I had that problem. Is it because update is called too often and hence it's not precise enough?

gaunt ice
#

you can duplicate the background eg AABC=>AABCAABC, once the first AABC less than some threshold or you see the second AABC then shift the first AABB to initial position, then you dont need to instantiate many times and use only one gameobject

modest dust
twin bison
modest dust
#

If you want something to be right next to each other then you need to spawn/move it relative to other objects in your scene or have some kind of grid/coordinate system

gaunt ice
#

if x<10 x can be 9 8 7 6 5... , that mean you cant just hardcode the value

modest dust
#

Basically imagine you have a huuuge lag spike and you're moving your background using transform.position = Time.deltaTime * ...

#

It's going to fly off the screen and then spawn a new tile way further away from the old one, because technically it did go past that hardcoded x pos value and the spawn is not relative to the old tile

twin bison
#

ok that makes sense now thank you very much

twin bison
zenith bobcat
#

Hello, i am making a endless runner game and took this code of the internet it supposed to generate levels aotumaticly and delete the old one,but, when i hit save code and go to unity to check it out the console stops me and say " invalid token";" in class, record, struct, or interface member declaration" i tried to at least know what is the console yappin about

eternal falconBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

desert current
twin bison
modest dust
#
Stack<Vector3> previousPositions = new Stack<Vector3>();

void Move(Vector3 position)
{
  previousPositions.Push(transform.position);
  transform.position = position;
}

void TryUndoMove()
{
  if (previousPositions.Count == 0)
    return;
  transform.position = previousPositions.Pop():
}```
desert current
#

An issue I was having is changing the Stack out of the void, so by simply "creating" the stack out of a void can solve this issue?

modest dust
#

What do you mean by "out of the void"

gaunt ice
#

it is called method not void, void is return type

modest dust
#

or in the Start() method, same result

desert current
worldly jolt
#

all my files are missing in the editor

desert current
#

I'll see if I can get it working now. Thanks.

worldly jolt
#

my files are gone in editor but in file exploror they are still there what happened help pls

#

i was just switching to webgl so i could put a build on itch.io for playtesting and they all dissapeared

#

but my game still works

#

where is bug report

modest dust
# desert current Yeah that's what I meant with "out of a void"

Just a reminder that value type fields are always initialized with their default value / default constructor so you don't need to initialize them in order to use them. Reference types (classes) on the other hand have a default value of null so you always have to explicitly call out their constructor before use, so either inline with the declaration or right before you need to use it

#

Good luck with the rest

kind cave
languid spire
fringe plover
#

!code

eternal falconBOT
naive lion
#

!code

eternal falconBOT
fringe plover
#

Hi, im making an 3D level editor, and i want spawned object to have Y pos same as Y pos in prefab, but it sets to 0... btw i didnt make this code, this is from tutorial, but i changed it to work with multiple grid layers, and when i spawn prefab it have correct Y pos, but when i drag it it changes to 0
Here is code:
BuildSys: https://hatebin.com/kaftarbzwa
ObjDrag: https://hatebin.com/fegqpovnbb

#

i was trying to fix that myself but it was too hard

languid spire
#

I would suggest that you add some debugging into GetWorldMousePosition and SnapCordinateToGrid so you can see what is happening

fringe plover
#

lemme try

languid spire
#

should have been your first action

fringe plover
#

and what im gonna do with it lol

#

it always giving me different Y

#

lemme try smth

#

nah, didnt help

#

i think something sets it to 0, like grid...

languid spire
#

that is the point of debugging the code, so you can see what is happening. show those 2 methods again

fringe plover
#

yeah

#

SnapCordinateToGrid Y is always 0

languid spire
#

but is celPos correct?

fringe plover
#

its not cuz of celpos i guess

#

it even sets Z to 0 everytime

#

maybe in ObjDrag i need to add og object Y to offset

#

not to offset

#

finally

#

i fixed

#

in line 33 i make it count og Y pos too

#

thank you for help

uncut bay
#

Hi

#

Having a bit of trouble

#

I'm starting off on unity and just playing around with making a 2d platformer and rn I have 2 portals, like in the image

#

I managed to code it so that when the player touches the bottom portal, the square appears in the top portal

#

but now I want to make it so that you can go back and forth between portals

rare basin
#

so make it the same you did

#

but other way around?

uncut bay
#

I tried

rare basin
#

any portal should have outcome

naive lion
#

reuse it and add a delay

uncut bay
#

but then it's jsut an infinite loopp

rare basin
#

portal A teleports to portal B

#

why is it in a loop

naive lion
uncut bay
#

I tried removing/putting back IsTrigger but I don't think I did it right

uncut bay
rare basin
#

google it

uncut bay
#

alr

uncut bay
#

and it'll just go back and forth

rare basin
#

then have a bool

naive lion
rare basin
#

canTeleport

#

and set it to true when you exit the trigger

uncut bay
#

I did do that

rare basin
#

so you portal

#

and canTeleport = false

#

you exit the portal trigger, set it back to true

uncut bay
#
    {
        if(collision.gameObject.name == "PortalExit")
        {
            portals = true; 
        }
        else
        {
            portals = false; 
        }
    }```
#

this was the code

#

then in another script I did this:

rare basin
#

that is really bad way of checking it

#

dont even check anything by name

uncut bay
#
    {
        CC = GetComponent<CircleCollider2D>();
    }
    private CircleCollider2D CC; 
    public InteractPortal triggering; 
    // Update is called once per frame
    void Update()
    {
        if (triggering.portals)
        {
            CC.isTrigger = false; 
        }
        else
        {
            CC.isTrigger = true; 
        }
    }```
rare basin
#

ever

uncut bay
#

how can I do it then?

rare basin
#

getcomponent

#

interfaces

#

even tags

naive lion
#

for ur simple project just do a tag check

uncut bay
#

do I give the tag to both portals

#

or should both portals have a unique tag

robust iron
#

changing asset file

desert current
#

!code

eternal falconBOT
naive lion
#

what u did for a beginner is great tho

#

keep trying your own methods

desert current
#

Stupid question, but how do I call a void that contains parameters? I want to call the Move void but it gives me an error. Here is the code:

    void Update()
    {
        if(greenSlime.isMove == true && canUndoSave)
        {
            Move();
            canUndoSave = false;
        }
    }

    public void Move(Vector3 position)
    {
        previousPositions.Push(transform.position);
        transform.position = position;
    }
timber tide
#

void is a return type

#

Look at the parameters between you calling your method and the parameters of the method. If it expects parameters, then you need to send something of that type into the method.

slate gale
#

hey guys I'm trying to make a video play audio but it won't work. I'm using the video player component, which plays the video fine, but no audio will play even though volume is on 1 and not muted (yes, i have audio listener on camera)

#

getting this error as well when I'm, trying to play example video in editor (outside working project)

slate gale
timber tide
slate gale
#

no code involved. simply dragged a video on an object and wont make sounds :C. should work just like this

#

my bad just realised this is code-beginner thx

desert current
modest dust
# desert current Stupid question, but how do I call a void that contains parameters? I want to ca...

Consider taking a pure C# course first if calling methods with parameters is already an issue.
Learning the basics first will definitely help. Otherwise it's kinda like trying to build a house without knowing what materials and tools to use, so you try and learn both at the same time and end up with a lego shack using random pieces from several lego sets sticked together using glue and tape instead of a proper brick house

#

Heard that w3schools C# course it good

desert current
neon fractal
#

why the unity executes this code section even though it shouldn't

slate gale
#

u should be getting an error with that ; behind if

gaunt ice
#

no, it wont cause any error

slate gale
#

rly?

gaunt ice
#

just fail silently

neon fractal
slate gale
#

ah i guess ur right

#

it just executes everything between ) and ; (which is nothing)

little garden
#

oof it got deleted

frosty hound
dusky oriole
#

Is there a way to initialize the fields of a class before Start is called but from the outside?

#

Like if I have a board and I don't want it to be of a fixed size, so I want to provide the height and width from the outside.

frosty hound
#

You can expose the fields in the inspector and set it manually. Or you can assign it in Awake function.

dusky oriole
#

Right but even in the Awake method they would have to be known in advance, I wouldn't be able to set them from outside.

languid spire
#

define 'outside'

dusky oriole
#

For example if I'm generating a level and the player gets to freely pick the size of the board. I can't have those be stored in the board class.

dusky oriole
frosty hound
#

You store the choice the player makes, somewhere. Such as in a GameManager, and read that when initializing your board.

dusky oriole
#

So the value has to be read by the board class itself?

#

What I'm looking for is to call the constructor of the board class and provide the dimensions that way, but with MonoBehaviour that's not an option.

languid spire
#

if your board is a prefab you can inject the values into the prefab immediately before instantiating it

dusky oriole
#

In code that is, not by assigning in the editor.

languid spire
#
GameObject prefab;
...
Board board = prefab.GetComponent<Board>();
board.height = ...;
board.width = ...;
GameObject go = Instantiate(prefab);
dusky oriole
languid spire
#

maybe, it depends what Init does

dusky oriole
#

sets the height and the width, but it doesn't work, Start gets called before that

languid spire
#

but you should not be using gridBoard after instantiation

#

also why Resources.Load just set gridBoard in the inspector

keen dew
#

Start isn't called immediately after instantiating. You can set the values after the Instantiate line.

languid spire
#

Start is being called on gridBoard because of the Resources.Load

#

I think that is where the confusion is

dusky oriole
#
[SerializeField]
GameObject _gridBoard;
// Start is called before the first frame update
void Start()
{
    _gridBoard.GetComponent<GridBoard>().Init(10, 10);
    Instantiate(_gridBoard, Vector3Int.zero, Quaternion.identity);
}

Welp, this also doesn't work.

#

Or wait, I'm still using _gridBoard

languid spire
#

again what is Init doing, show the code

dusky oriole
#
public void Init(
    int width,
    int height
)
{
    _boardWidth = width;
    _boardHeight = height;
}
languid spire
#

that's fine, so now you just need the GameObject returned from Instantiate

dusky oriole
#

I'm confused. We assign the prefab in the editor -> set values in its script -> instantiate the prefab and only at that point does Start get called?

languid spire
#

yes

shrewd swift
#

i got this error when loading a scene in editor

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

details

System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <605bf8b31fcb444b85176da963870aa7>:0)
System.Collections.ObjectModel.ReadOnlyCollection`1[T].get_Item (System.Int32 index) (at <605bf8b31fcb444b85176da963870aa7>:0)
UnityEngine.Rendering.HighDefinition.StaticLightingSky.InitComponentFromProfile[T] (T component, T componentFromProfile, System.Type type) (at ./Library/PackageCache/com.unity.render-pipelines.high-definition@14.0.8/Runtime/Sky/StaticLightingSky.cs:228)

i cant find where is that "static light"

keen dew
dusky oriole
keen dew
#

No it doesn't, it returns whatever you pass to it

languid spire
dusky oriole
modest dust
#

But Nitku pretty much provided the easiest solution

keen dew
#

In that case no because the previous lines modify the prefab

#

but there's no reason to do that in this case

dusky oriole
#

At this point I'll just post all the code:
GameManager.cs

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

public class GameManager : MonoBehaviour
{
    [SerializeField]
    GameObject _gridBoard;
    // Start is called before the first frame update
    void Start()
    {
        var board = _gridBoard.GetComponent<GridBoard>();
        board.Init(10, 10);
        Instantiate(board, Vector3Int.zero, Quaternion.identity);

        //_gridBoard.GetComponent<GridBoard>().Init(10, 10);
        //Instantiate(_gridBoard, Vector3Int.zero, Quaternion.identity);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

GridBoard.cs

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

public class GridBoard : MonoBehaviour
{
    private int[,] _board;
    private int _boardWidth;
    private int _boardHeight;

    [SerializeField]
    private Tilemap _tilemap;
    [SerializeField]
    private Tile _whiteTile;

    public void Init(
        int width,
        int height
    )
    {
        _boardWidth = width;
        _boardHeight = height;
    }

    void Start()
    {
        Debug.Log(_boardWidth);
        Debug.Log(_boardHeight);
        _board = new int[_boardWidth, _boardHeight];

        GenerateTileMap();
    }

    private void GenerateTileMap()
    {
        for (int i = 0; i <  _boardHeight; ++i)
        {
            for (int j = 0; j < _boardWidth; ++j)
            {
                _tilemap.SetTile(new Vector3Int(j, i, 0), _whiteTile);
            }
        }
    }
}

The console always prints 0 0, it doesn't set the dimensions.

keen dew
#

So did you try what I suggested?

modest dust
halcyon summit
#

Has anyone ever experienced this? I'm destroying all objects with a certain tag, then straight after, running a Find for all objects with that tag, checking the Length of the array, and seeing that all the objects are still there?

modest dust
#

the order of method calls will be Awake, Init, Start

keen dew
keen dew
halcyon summit
dusky oriole
modest dust
#

Simply drag the prefab with that script attached

keen dew
#

...the same way you set it when it was a GameObject?

dusky oriole
#

I can drag the prefab, which is what I'm currently doing. It has a script attached to it called GridBoard.cs

modest dust
#

Then what's the issue

red ivy
#

how are those called?

#

In general I mean those:

modest dust
#

methods?

dusky oriole
#

Right...
Guess this has hit a dead end. I appreciate the help regardless 👍

modest dust
dusky oriole
#

Already did, still prints 0 0

#

Like I said, don't worry about it.

modest dust
#

Show code where it prints 0 0

covert matrix
#

im trying to make a scene that displays certain values about the player's attempt at a stage, e.g. their name, scores, etc.
could i ask for suggestions on how to make the scene create a new button that is created for each attempt of the player? sort of like a spreadsheet and its tabs

wintry quarry
dusky oriole
keen dew
#

It's possible to drag it because the [SerializeField] attribute literally means that

dusky oriole
#

When I tried it before I simply ran Init() on the script of the prefab, which was confusing to me then and now it makes sense because it's simply the wrong thing to do xD

dusky oriole
keen dew
#

and it makes sense to instantiate the class you want instead of GameObject because then you don't need to do an extra GetComponent on it

#

You'd still be dragging the same object but you get direct access to that specific component

dusky oriole
#

This is... weird. Prefabs just fill in whatever role we need it to?

keen dew
#

no

dusky oriole
#

So long as a prefab has that script it attached it can be dragged into that slot?

keen dew
#

yes

modest dust
keen dew
#

You're already doing the same thing in the other script

#
    [SerializeField]
    private Tilemap _tilemap;
    [SerializeField]
    private Tile _whiteTile;
keen dew
#

those do the exact same thing but with Tilemap and Tile instead of GridBoard

dusky oriole
#

Why does instantiating the prefab or the script attached to it achieve the exact same result? Because in reality the dragged object is still the prefab?

dusky oriole
keen dew
#

Yes, and both of those are GameObjects like everything else

dusky oriole
#

Oh I see

#

Well, all's well that ends well, arduous.

#

Thanks everyone 👍

wooden minnow
#

how would i get the exact center between 2 objects?

north kiln
wooden minnow
#

ok now i feel dumb

modest dust
dusky oriole
#

How does it follow that Start is called after my Init method from this description:

Start is called on the frame when a script is enabled just before any of the Update methods are called the first time.

#

Is it just that a given Start method is guaranteed not to be interrupted or something? So if we call Instantiate and then Init within the same scope there won't be a problem?

swift crag
#

you're going to have to show us your code

#

Init is not a method Unity knows or cares about

swift crag
#

If you mean you're doing something like this..

#
var obj = Instantiate(thing);
obj.Init();
#

then yes, it's expected for Start to run after Init

#

oh, that's interesting -- I went and tested to be sure. I didn't know that Update didn't run on frame 0!

dusky oriole
swift crag
dusky oriole