#💻┃code-beginner

1 messages · Page 409 of 1

ivory bobcat
#

Doesn't look specific to Unity, maybe try !csds

eternal falconBOT
random cave
#

Im trying to make a marker for my minimap, I can move around the map with right click and left click is suppose to move the marker to cursor place, but the coordinates are wrong, how do I fix this?:
This checks if your mouse is over the map.

    {
        PointerEventData EventDataCurrentPosition = new PointerEventData (EventSystem.current);
        EventDataCurrentPosition.position = new Vector2 (Input.mousePosition.x, Input.mousePosition.y);
        List<RaycastResult> result = new List<RaycastResult> ();
        EventSystem.current.RaycastAll (EventDataCurrentPosition, result);
        return result.Count > 0;

    }```
**This moves movePoint2 to where the mouse hit.**
```if (IspointerOverUiObject ()) {
            if (Input.GetMouseButtonDown (0)) { 


                ray = cam.ScreenPointToRay (Input.mousePosition);


                if (Physics.Raycast (ray, out hit, Mathf.Infinity, mask)) {

                    movePoint2 = new Vector3 (hit.point.x, hit.point.y, hit.point.z - offset);
                }
            }
        }```
polar acorn
#

That returns an int. You can just use >

river quiver
polar acorn
river quiver
#

but it has to be at night

polar acorn
#

Right

river quiver
#

so like you know when its night time and its dark

polar acorn
#

It'd be either after 21 or before 6

#

So why use &&

#

when it's an or

river quiver
#

aaaaaa okay

#

damn

#

mb

#

shi

#

xd

#

ty

cosmic dagger
#

Try speaking in complete sentences . . .

crisp anvil
#

What am I doing wrong here? Everything works correct except checking if the tile is blacklisted and should return false.

    public Tile[] BlacklistedTiles;

    public bool CanSpawnOnTile(Vector3Int tilePos)
    {
        TileBase tile = GameMap.GetTile(tilePos);
        if (tile == null)
        {
            return false;
        }
        if (BlacklistedTiles.Contains(tile))
        {
            return false;
        }
        if (!IsWithinSpawnDistance(tilePos))
        {
            return false;
        }
        return true;
    }
    public void GetSpawnPoints()
    {
        for (int x = GameMap.cellBounds.xMin; x < GameMap.cellBounds.xMax; x++)
        {
            for (int y = GameMap.cellBounds.yMin; y < GameMap.cellBounds.yMax; y++)
            {
                Vector3Int localPlace = new Vector3Int(x, y, 0);
                if (CanSpawnOnTile(localPlace))
                {
                    Vector3 place = GameMap.GetCellCenterWorld(localPlace);
                    spawnPoints.Add(new Vector2(place.x, place.y));
                }
            }
        }
    }
eternal needle
ivory bobcat
crisp anvil
#

It's adding spawn points ontop of blacklisted tiles, I added a Debug log in the

        {
            return false;
        }```
And it never gets called. The tile is added to the array in the inspector.
#

I figured it out

#

I had two tile maps one named obsticles and another for the ground, the ground is the tilemaop attached to the script that was painted under the Blacklisted tile in the other tilemap. Erasing the painted ground tiles under the obsticles fixed it. cause then it returns null.

        if (BlacklistedTiles.Contains(tile))
        {
            return false;
        }

Pretty sure with the setup I have this code becomes unreachable.

#

still worth having for future tiles that might not want things to spawn on.

brave pecan
#

Hello everyone, im learning about 2d games. I want to do some practice. Can you guys suggest me any game idea for reinforce my basic knowledge? i made a quiz game and a basic platformer. I want to try something different.

ivory bobcat
#

What do you want to focus on?

brave pecan
ivory bobcat
brave pecan
#

okay sorry

rocky canyon
#

are Queues<> expensive??

#

hm.. i found something about Circular Buffers

teal viper
remote osprey
#

Hello

#
foreach (int i in Enumerable.Range(0, 2))
{
    GameObject column =  Instantiate<GameObject>(new GameObject("Column"),CardGrid.transform);
    column.AddComponent<VerticalLayoutGroup>();
    foreach (int j in Enumerable.Range(0, 2))
    {
        GameObject cardObject = Instantiate<GameObject>(CardPrefab, column.transform);
        Card card = cardObject.GetComponentInChildren<Card>();
        card.Initialize(chosen[i*3+j]);
    }
}

Any specific reason this code would fail when i*3+j = 4?

#

I keep debugging but have no idea why

#

It's supposed to create columns of 3 cards but it only creates 2 columns of 2 cards before giving ArgumentNullException...

#

Curiously, it creates 2 columns outside of CardGrid, which is insane

orchid hatch
#

Hey! Anyone have an idea for the simplest way to know which direction is the shortest distance between two points on the circumference of a circle? Once my enemy comes into a radius around the player it rotates around the player until it reaches a collider (player's gun) . I want to make sure it always rotates in the direction that is the shortest distance.
It's a little over my head so if you know where to start lmk!!
Thanks :)
Working in Unity w/ C#

cosmic dagger
# rocky canyon are `Queues<>` expensive??

Nah, it just depends how you're using it. A Queue<T> is for constantly adding and removing elements as those operations are fast, but you cannot index specific elements. If you need to access specific elements (indexing), then List <T> is preferred as removing and adding are expensive . . .

fading mountain
#

Hey guys. Im working on a quiz game and currently trying to implement the ability to select from a list of quizzes - for example, a quiz about computers, a quiz about video games, etc. - I have one list for each quiz that has a certain number of scriptable objects with the question and answers. I want a way to add these lists of scriptable objects to another list called quizzes so that I can access them by an index number and populate the questions and answers in the quiz. How would I go about doing that? Is there a better way to do this rather than a list of lists?

cosmic dagger
#

You can do it manually or write code to add all quiz SOs to the list automatically . . .

rocky canyon
#

it runs every frame so i was curious

#

ya, i might use a fixed array

#

float[] frameRates = new float[BufferSize];

cosmic dagger
rocky canyon
#

ok thanks 👍 i wanted someone more experienced to give it a look

remote osprey
#

Distances don't have a direction

#

You could think of the direction from A to B or from B to A

orchid hatch
#

I think I need to calculate which angle is smaller ("left" or "right" of the enemy towards the gun) and then choose whichever direction is along the smaller angle

rocky canyon
#

i think he means like if the guy is almost turned 45* away from the direction it should look.. instead of rotating around the opposite direction 315* it rotates back the 45* rotation

orchid hatch
#

yeah exactly

rocky canyon
#

i think ive used Atan2 for that

remote osprey
#

You could use dot product between OA and OB

#

Where O is the center of the circunference

#

If it's negative, then A is "up" B, therefore rotate - (360 - angleAB)

#

If it's positive, then B is "up" A, therefore rotate angleAB

#

I just took this off my head so it might not work as I have no way to pen test this xD

#

@orchid hatch

orchid hatch
#

thanks for the replies

#

is "OA" a vector A - O?

remote osprey
#

Yes

#

I used linear algebra solution

orchid hatch
#

so I would do Vector3.Dot(OA,OB) ?

remote osprey
#

yes

#

Then check the sign

#

I'm gonna try drawing something

orchid hatch
#

okay i think this makes sense to me

#

thank you!

#

I'll try it & lyk

remote osprey
#

you're welcome!

#

Hope it works for you c:

remote osprey
#

what you should use is the dot product between OA and Rot90(OB)

#

Because that way, if the sign changes it means crossed OA

#

in other words:

#
var dot = OA.x*-OB.y + OA.y*OB.x;
if(dot > 0)
    console.log("OB on the right of OA")
else if(dot < 0)
    console.log("OB on the left of OA")
else
    console.log("OB parallel/antiparallel to OA")
rocky canyon
#

antiparallel eh?

remote osprey
#

I guess both are parallel lol

rocky canyon
#

😄 lol

#

var dot = OA.x*-OB.y + OA.y*OB.x; lookin scary

#

i always have to look back on dot, cross, and atan

remote osprey
remote osprey
rocky canyon
#

bout to make a gun turret, i'll be doing this myself soon

remote osprey
remote osprey
#

Wanna see the result :p

orchid hatch
#

It seems to give inconsistent results depending on where it approaches from

#

oh i just saw the scratch that

#

nvm

remote osprey
orchid hatch
#

haha

#

ok i'll try this!

#

i think it works!

#

though it gave the seemingly wrong direction a couple times but every other time it's right

#

it seems like there's one specific approach that confuses it

#

i'll take a video

#

rats

#

here's my code ignore the direction bool lol

remote osprey
#

Oh ok, so the player is that little dog, right?

#

And the pistol(collider) is the cursor?

#

Oh, my mistake

#

try dogToBat.x * (-dogToTarget.y) and see if it resolves

orchid hatch
#

the player is the dog and the bat's target is where the bone/gun is

remote osprey
#

it should be a minus sign

orchid hatch
#

rather a point thats slightly between the bone and the cursor

#

a minus sign where?

orchid hatch
late burrow
#

is tostring still works on class that is null

remote osprey
#

I used the wrong sign and misled you, sorry :p

orchid hatch
#

oh my bad i missed the minus sign that was there in your original response

remote osprey
#

You didn't miss it, I edited it later xD

orchid hatch
#

oh true

#

that works!!

#

tysm

remote osprey
#

You're welcome!

#

I'm happy to help 😄

orchid hatch
cosmic dagger
remote osprey
#

I your pixel art, it has such a light feel to it :p

orchid hatch
#

thanks!

#

hoping to finish this 1 up & put it out soon

remote osprey
#

I hope you do!

#

I really feel like playing this, feel free to tag me when you release it :p

orchid hatch
#

cool will do!!

icy tree
#

Hey, I’m looking to start programming what do you guys recommend that I learn first

remote osprey
#

I'd you can start with anything you like!

#

If you want to get into gaming, you could try using something simpler like GameMaker

#

But if you just want raw programming, you could pick any of the major languages, really

#

Like Java, C#, Python, whatever is more directed to what you want

cosmic dagger
remote osprey
teal viper
icy tree
orchid hatch
#

for what it's worth I found the way gamemaker simplifies things and uses visual scripting to be kind of confusing as a beginner & it was more useful to just start learning c# by messing around in Unity and looking up things that I didn't understand

cosmic dagger
remote osprey
#

I both like and despise C

#

It gives me so much control but but

#

(Segmentation Fault)

bold plover
#

Any opinions on when to run the initialization for my state machine? Trying to decide between Start() and Awake. The former seems the most stable but I'm not sure if that's a good take.

remote osprey
#

Start runs after Awake

#

It really depends on what your needs are

slender nymph
#

use Awake to initialize its own variables, then Start to access other objects

bold plover
#

Gotcha. Thank you! I was reading the page but the dots weren't connecting in my brain.

#

And the order in which they execute is the opposite when initializing during gameplay?

cosmic dagger
bold plover
#

Got it. So it's *not *a reversal and more so the order in which they execute? GameObject already existing will do Awake() into Start(), and then another Awake() runs after that for the instantiated ones?

summer stump
# bold plover And the order in which they execute is the opposite when initializing during gam...

Awake and start are called in the same frame. So objects that exist when runtime starts will have both called the first frame of runtime (with the first start being called AFTER every awake). An instantiated object may be called IN that first frame, but I believe the object isn't actually created until the very start of the next frame? It will at least be later no matter how soon Instantiate is called

bold plover
#

ahh

summer stump
slender nymph
#

start by learning to code. there are beginner c# courses pinned in this channel

#

then why are you here

naive pawn
#

coding is kinda necessary to make anything with logic

#

it doesn't have to be writing code, unity has a visual scripting system

#

but you will still have to create logic

slender nymph
#

my guy, how are you going to go into a code channel, ask how to get started with unity, then say you don't want to learn to code

naive pawn
#

drag thingys
if by that you mean blocks, yes, unity has visual scripting.
watch yt
you could do that to learn, but you can't just copy everything forever

#

you actually have to learn

#

why would being 2d have an influence on being multiplayer

slender nymph
#

you absolutely need to learn to code if you want to do anything remotely related to multiplayer

naive pawn
#

if you want it to have multiplayer, you have to make your game support multiplayer

#

learn

#

there's resources in the pinned message

#

you've been told that already

#

you don't, not yet.

#

learn to actually make it first

#

then add multiplayer

#

don't get ahead of yourself, you'll just create a nightmare for your future self

queen adder
#

guys, ive been learning the creative core thing but yeh i mean it gets you through how to a 3d environnement which is fine but i thought i need much that 3d knoweldge for a mobile game

#

like i would more interested in like the architecture of a mobile game for exemple, idk how to explain it yeh yeh designing a 3D environement isnt it cuz 3d environnement will be like 1/5 of my game

naive pawn
#

....ok, what's your question?

queen adder
#

hmm my question like where could i learn that i guess

naive pawn
#

learn... what?

#

aside from user interfacing, a mobile game isn't much different from any other environment

eternal needle
#

you can google for tutorials on how to make multiplayer games. no one here is gonna spoonfeed u all that you are looking for, especially since you said you dont wanna code

naive pawn
#

probably not an import, the environments are fundamentally different

eternal needle
#

repeating the question is just spamming, this isnt even a code question.

naive pawn
#

if you can make a fully functioning game in scratch then you already know how to write logic

#

just rewrite that logic using stuff unity understands

#

there's no shortcut for this

#

ok, go learn then

#

plenty of resources exist

#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

summer stump
#

It would take weeks of one on one help to "just tell you".
You need to put in the work yourself. If you have SPECIFIC questions, we can help. But you're questions are simply not how any of this works.
People pay a lot of money for what you are demanding for free

timber comet
#

yes

queen adder
#

this guy must be a troll

summer stump
#

Learning c++ and spending the time learning

#

Ask in an unreal server

#

But first put a tiny bit of effort in by yourself.

#

<@&502884371011731486>

#

They can see deleted comments. Clearly not a misclick

#

You are the type of person that is going to struggle really hard

north kiln
#

!ban 1145876377992712242 offensive crap

eternal falconBOT
#

dynoSuccess chatisbest101 was banned.

queen adder
#

is there some guide out here to learn the basics principles of an idle (plays itself) mobile game rpg style? i know i could do it how i think it should be done but im sure il shoot myself in the foot and waste big amounts of time to implement stuff that is already establish

chrome shadow
#

where would i store variables such as volume and player health? in a GameManager script attatched to an obj, scriptable object, static float... im really confused
the main point is i need them to be adjustable / updated across scenes

slender nymph
#

store them in an object that makes sense to have them. for example why would the GameManager need either of those variables? the player's health should be stored on whatever component manages its health, and the audio volume should be stored on whatever deals with changing the volume

chrome shadow
#

im not sure how to overcome this problem

slender nymph
#

This isn't necessarily what you need to do, but what I personally do is put my settings into a static class, when the game is launched I load the settings from disk and apply them to that static class. Then when something has changed them I save the settings to disk again.

chrome shadow
#

so should i have the same SoundManager on both scenes?

slender nymph
#

if you are using a singleton instance to manage that though, you'll need some way to ensure that an instance of that singleton exists. either by putting extra copies into your scenes, or by instantiating it when it doesn't exist

chrome shadow
#

ahhh ok

dreamy dune
#

public void EjectObject(Item item)
{
if (item == null || item.quantity <= 0 || item.ground_prefab == null)
{
return;
}

    GameObject g = Instantiate(item.ground_prefab, drop_Target.position, drop_Target.localRotation);

    if (g.GetComponent<Rigidbody>())
    {
        Rigidbody r = g.GetComponent<Rigidbody>();
        r.AddForce(playerCam.transform.forward * EjectForce / r.mass);
    }
}****
#

can anyone help me why my object is spawning like 5 meters away from me and in wrong rotation

#

its just not spawning at target_drop

burnt vapor
eternal falconBOT
subtle garnet
#

Hello guys! This code sets a ScriptableObject parameter in ScriptableObjects at runtime, but when I stop running it, it's not saved anymore in the ScriptableObject. Why?

private void ApplyDinosaurDataToItems()
    {
        DinosaurItem[] dinosaurItems = Resources.LoadAll<DinosaurItem>(dinosaurItemsPath);

        foreach (DinosaurItem dinosaurItem in dinosaurItems)
        {
            dinosaurItem.dinosaurData = Resources.Load<DinosaurData>(dinosaurDatasPath + $"/{dinosaurItem.name}");
        }
        
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
languid spire
subtle garnet
languid spire
subtle garnet
languid spire
#

no it wont

#

SO's are immutable in a build

subtle garnet
#

Oh sorry, I didn't mean it like that. I won't use this in build.

#

I thought you mean the ScriptableObjects won't work. Sorry!

crimson ibex
#

I have a problem with Collision2D.
I have multiple gameobjects (counters) close to each other. I need my "player" gameobject to collide with one. But "player" tends to collide with 2 counters at same time.

My solution - Can be ignored - spent 3 days.
I solved that by changing layer of "counter" dynamically to "collidable", based on my what "player" must collide next. And setting up my layers such that the other counters dont initiate "CollisionEnter2d". And on CollisionExit , I change back the layer to "non-collidable".
Now, I have N no. of player gameobjects, that can collide as their algorithm dictates. There is no user input.
My use case is , any player can collide with any counter.
So, if I have changed counter layer to "collidable" for 1 player, other players may collide it by mistake.
And I can not control when to disable "Collidable" state, as other player may have same target.

What other way I can solve this ?

crimson ibex
languid spire
crimson ibex
#

Ohk ! That sounds promising. Thanks a lot @languid spire

river quiver
#

i dont understand what is singleton coding pattern?

burnt vapor
#

It is useful for things like managers that usually only have one instance in the game. You can easily access it and its data this way.

half egret
#

Unity had a great live session explaining/highlighting how to use singleton patterns, but I can't seem to find it anymore. That's where I'd usually direct people

burnt vapor
atomic yew
#

How can I assign Gameobjects in different scenes to scripts?

languid spire
#

because it can only be done at runtime

atomic yew
barren vapor
languid spire
burnt vapor
#

Two out of three cons also apply here. Only the coupling one, which I'd argue doesn't really matter for a beginner

atomic yew
#

Ok

atomic yew
ripe shard
languid spire
crimson ibex
#

Physics2D.IgnoreCollision(player.GetComponent<Collider2D>(), counter.GetComponent<Collider2D>(), false);
When I make IgnoreCollision false, the collisionEnter2d is not called,

#

Is that expected behaviour , for IgnoreCollision

languid spire
frank zodiac
#
charactersPerSecond.ToString();
charactersPerSecond = tagValue;

tagvalue is a string and CPS is a float. i get a red squiggly line on tagValue that says cannot convert string to float. any ideas??

crimson ibex
barren vapor
frank zodiac
barren vapor
# frank zodiac yes

You're reaching it wrong. You're basicly doing:

  • Turning charactersPerSecond into a string, but do nothing with it.
  • Trying to attach a string to charactersPerSecond (which is still a float)
frank zodiac
#

thats why i tried seperating them

barren vapor
frank zodiac
barren vapor
#

You can't do that. C# doesn't work like that

barren vapor
#

C# isn't dynamically typed like Python

frank zodiac
eager spindle
barren vapor
#

create a new variable

#

wait

#

no

frank zodiac
barren vapor
#

that doesn't work either

frank zodiac
#

how

burnt vapor
#

is the issue that the value you try to assign is a string?

#

This sounds like an XY problem so please explain

eager spindle
#

wait are you setting tagValue to newCharacterPerSecond or the other way round

barren vapor
barren vapor
#

you're turning it around I think.

frank zodiac
frank zodiac
barren vapor
#

So:

tagValue = charactersPerSecond.ToString();
frank zodiac
#

its suppoed to be CPS = tagvalue

barren vapor
#

I think you need that

eager spindle
#

characterPerSecond is a number, tagvalue is a string.
you want to convert tagValue to a number, done like int.parse(tagValue).
afterwards you can set characterPerSecond to tagValue

burnt vapor
frank zodiac
burnt vapor
#

Yeah nobody is helping you with an actual answer here

#

Your use case seems unnecesarrily complex

eager spindle
barren vapor
burnt vapor
#

Parsing cps:9 into assigning 9 sounds too complex

#

Why do you need to do that?

eager spindle
burnt vapor
#

Is the point of this code to set a variable based on its prefix?

#

I mean, I can answer it, but there's a lot of parsing involved

barren vapor
eager spindle
burnt vapor
#

I don't think half the people here read the actual question

frank zodiac
burnt vapor
#

If you really, really want to have something like this, determine the location of :, and get the string part before it and after it

frank zodiac
#

tagValue is the second half of a string called tag which I just split with a variable

burnt vapor
#

Then, int.TryParse the part after the semicolon and you can assign the result to the variable related to the part before

frank zodiac
burnt vapor
frank zodiac
eager spindle
eager spindle
#

ok yea then you can definitely int parse tagvalue

frank zodiac
#

this?

eager spindle
#

yuh

frank zodiac
eager spindle
#

if it works you should know about dictionaries too

#

rather than using this tag system

crimson ibex
frank zodiac
eager spindle
#

ah ok

#

good luck 🫡

burnt vapor
crimson ibex
#

some day I will write some test code to confirm. too tired today.

burnt vapor
#

Like I said, this is complex and I don't see what this achieves

frank zodiac
eager spindle
#

woah

#

are you trying to read an ink file?

frank zodiac
#

i want to change the speed at which the character talks to add drama and stuff

frank zodiac
#

i mentioned that before

eager spindle
#

i heard of it i should prob give it a go soon

frank zodiac
#

should cost money but its free for some reason

eager spindle
#

in all honesty the format isnt that hard

#

but i think its a good start

#

a lot of people write their own node based dialogue manager when ink exists

crimson ibex
#

thank you @languid spire my use case is solve with Ignore Collision.

frank zodiac
eager spindle
#

editor tools spinning

frank zodiac
#

charactersPerSecond = float.Parse(tagValue);

eager spindle
#

any error?

#

is charactersPerSecond an int or float?

frank zodiac
#
text.maxVisibleCharacters++;
yield return new WaitForSeconds(1f / charactersPerSecond);

this is the thing im using for characters per second by the way

frank zodiac
frank zodiac
eager spindle
#

try printing out tagValue and charactersPerSecond to see

frank zodiac
#

..... weird, this is what it printed out. even tho in the ink file i set the cps to be 20 but it says 0.05

#

and tagvalue 20

eager spindle
#

20 * 0.05 = 1

#

if that is of interest

frank zodiac
#

okay nevermind it works

#

i accidentally commented out something

#

thanks for your help

eager spindle
#

🎊

hallow acorn
#

guys please help me i set up my first person movement in unity and idk why it always moves me into one direction. I also tried to comment out some of the areas which have effect on the position one at a time to find the section with the error but i couldnt find anything

#
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [Header("Movement")]
    public float moveSpeed;

    public Transform orientation;

    float horizontalInput;
    float verticalInput;

    Vector3 moveDirection;

    Rigidbody rb;


    private void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true;
    }

    private void Update()
    {
        InputHandler();
    }

    private void FixedUpdate()
    {
        MovePlayer();
    }


    private void InputHandler()
    {
        horizontalInput = Input.GetAxisRaw("Horizontal");
        verticalInput = Input.GetAxisRaw("Vertical");
    }
    private void MovePlayer()
    {
        //Calculate movement direction
        moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
        rb.AddForce(moveDirection.normalized * moveSpeed, ForceMode.Force);
    }

}```
thats the main code of my project everything else is just a script to move the camera to an empty object attached to my player and the script to rotate the camera
hallow acorn
languid spire
#

Debug your values so you KNOW what you are dealing with

eager spindle
#

are you sure orientation is rotating

hallow acorn
#

wait

#
{
    public float sensX;
    public float sensY;

    public Transform orientation;

    float xRotation;
    float yRotation;

    private void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    private void Update()
    {
        //get Mouse Input
        float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
        float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;

        yRotation += mouseX;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        //Rotate cam and orientation
        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
        orientation.rotation = Quaternion.Euler(0, yRotation, 0);

    }

}```
thats the script i use to rotate the camera
eager spindle
#

ok so is orientation set to the camera?

#

i dont know where orientation is in your scene

#

if it's even rotating

hallow acorn
eager spindle
#

play the scene and check if orientation is rotating

#

and look more into debugging your code

hallow acorn
eager spindle
#

try pressing this big green button

hallow acorn
#

ok wait

eager spindle
#

this is a fun watch

hallow acorn
#

ty

eager spindle
#

i didnt know about the big green button until 1.5 years into unity 😄

#

even though i learned c++ beforehand I didnt know you can debug unity

languid spire
#

tbh 'Attach to Unity' is a bit of a hint

eager spindle
#

i never looked at it tbf

languid spire
#

rofl

eager spindle
#

since unity is the one running the game

timber comet
languid spire
#

of course, that's what it is for

#

it 'Attaches' your VS 'to' your 'Unity' project so you can debug in VS

eager spindle
#

are there any drawbacks to enabling debugging for all projects

#

i had that on for a while now

fading seal
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class fridgeScript : MonoBehaviour
{
    public GameObject inticon, fridge, fridgeOpened, fridgeClosed;
    
    
    void OnTriggerStay(Collider other){
        if(other.CompareTag("MainCamera")){
            inticon.SetActive(true);
            if(Input.GetKey(KeyCode.E)){
                fridgeClosed.SetActive(false);
                fridgeOpened.SetActive(true);
                fridge.SetActive(true);
                inticon.SetActive(false);
            }
        }
    }
    void OnTriggerExit(Collider other){
        if(other.CompareTag("MainCamera")){
            inticon.SetActive(false);
        }
    }
}``` is there a simple way to make the door close if i were to press e again?
languid spire
#

only speed

teal viper
eager spindle
#

idk

hallow acorn
eager spindle
#

the 1.5 year mark where everyone learns about the big green button

fading seal
# eager spindle just set fridgeopen to inactive fridgeclosed to active

like this? ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class fridgeScript : MonoBehaviour
{
public GameObject inticon, fridge, fridgeOpened, fridgeClosed;

void OnTriggerStay(Collider other){
    if(other.CompareTag("MainCamera")){
        inticon.SetActive(true);
        if(Input.GetKey(KeyCode.E)){
            fridgeClosed.SetActive(true);
            fridgeOpened.SetActive(false);
            fridge.SetActive(true);
            inticon.SetActive(false);
        }
    }
}
void OnTriggerExit(Collider other){
    if(other.CompareTag("MainCamera")){
        inticon.SetActive(false);
    }
}

}```

full kite
#

I got a big question if anybody can help me. I setted the Canvas Scaler to 1920x1080 ; The canvas render mode to the main camer. I putted some UI, anchored and when I change the resolution from 1920x1080 to device resolution 1560x720, the UI moves a bit and its uncentered as he needs to be. Anybody can help? To anchor the UI even more, so it doenst matter the resolution, UI stays the same?

timber comet
hallow acorn
eager spindle
# full kite I got a big question if anybody can help me. I setted the Canvas Scaler to 1920x...

thats normal, look into how unity UI works.
https://www.youtube.com/watch?v=QnT-2KxVvyk

This tutorial/guide will show you how to resize your Unity UI canvas, GameObjects, text, button and images. You will learn:

  • How to fix Unity UI for every resolution
  • How to adapt UI for mobile devices
  • How to change Unity UI canvas scaling

💜 Join our Discord: https://discord.gg/hNnZRnqf4s

Timestamps:
0:00 - Intro
0:20 - Fixing main UI
3:23...

▶ Play video
full kite
#

Thank you

eager spindle
#

tldr use this tab

languid spire
eager spindle
#

its a standard across a lot of UI editors. Figma has a near identical system. Godot lets you use either position or the standard anchors

fading seal
eager spindle
timber comet
fading seal
eager spindle
#
bool yourBool = true;
Debug.Log(yourBool); // returns true
Debug.Log(!yourBool); // returns false```
#

we'll talk about ? another day 😴

full kite
#

@eager spindle I got 12 UI Images that are around the screen. Can I put all of them to the left side and then arrange them even tho some are the center or some are to the right?

eager spindle
#

idk what that looks like

fading seal
full kite
#

The idea is that I spawn some gameobjects around the screen. I arrange them with anchor and position through code but its work only one one resolution. With anchor and pivot

eager spindle
#

do not copypaste my code it is ass

#

and its not related to what youre doing

timber comet
eager spindle
#

if youre not sure on what it does you should learn c# basics before going to unity

#

some people do wing it through unity but waste a lot of time because they dont understand basic coding concepts

timber comet
#

So, you should take the state of your door in start(), save it into a bool, then when you check for your input, you set the setactive to !yourbool (you need to save the changes also to your bool, so the best is to set first when you get the input your bool to = !YourBool and then in the setactive(YourBool))

timber comet
timber comet
timber comet
fading seal
timber comet
#

In Start you need to get if your door is closed or open, you can get that by checking if fridge open or fridge closed is active or not

timber comet
#

No, it’s a function of Unity

#

You need to write in your code void Start()

fading seal
burnt vapor
burnt vapor
#

Works fine, just adviced to use bool

burnt vapor
#

It's an alias

timber comet
#

Because if you press e you will get what you want only once

hallow acorn
timber comet
burnt vapor
#

You don't need two booleans

fading seal
burnt vapor
#

Do you know what a boolean is?

fading seal
eager spindle
burnt vapor
#

Yes, but what is the point of a boolean?

eager spindle
#

how does it help you here

burnt vapor
#

I think you are lacking some very basic c# fundamentals and I strongly advice you learn those first instead of making a game

fading seal
safe radish
burnt vapor
#

Not only is c# way different in Unity, you are effectively trying to learn two frameworks

timber comet
eager spindle
fading seal
timber comet
#

you said yes or no tho

fading seal
fading seal
timber comet
hallow acorn
barren vapor
eager spindle
#

minecraft font all over my system

#

its inconsistent though

barren vapor
eager spindle
#

in this image the new win10 font is used

timber comet
hallow acorn
fading seal
# timber comet Yes
using UnityEngine;

public class fridgeScript : MonoBehaviour
{
    public GameObject inticon, fridge, fridgeOpened, fridgeClosed;
    bool open = true;
    
    void Start(){
        fridgeOpened.SetActive(false);
        fridgeClosed.SetActive(true);
    }
    void OnTriggerStay(Collider other){
        if(other.CompareTag("MainCamera")){
            inticon.SetActive(true);
            if(Input.GetKey(KeyCode.E)){
                fridgeClosed.SetActive(true);
                fridgeOpened.SetActive(false);
                inticon.SetActive(false);
            }
        }
    }
    void OnTriggerExit(Collider other){
        if(other.CompareTag("MainCamera")){
            inticon.SetActive(false);
        }
    }
}``` right now if i press e it stays closed
hallow acorn
timber comet
burnt vapor
#

Also

#

Why not just move the door

#

Why set something as active/inactive

fading seal
eager spindle
#

we are not giving you code here and can only tell you so much

#

learn about the big green button today

#

it will help you understand what youre typing

burnt vapor
#

You currently complicate this way too much

timber comet
hallow acorn
burnt vapor
#

and I don't see the boolean being changed. You are merely using it in a method

timber comet
fading seal
burnt vapor
# fading seal this?

Refactor your code so there is a single door. Put the door in a closed state, and then on opening the method will call isOpen = !isOpen;
Then, make an if statement that sets the door transform to the correct location

hallow acorn
burnt vapor
timber comet
fading seal
burnt vapor
#

Ah okay

hexed terrace
# hallow acorn

press play on unity BEFORE starting to record.. so that the first 50% of your video isn't you pressing play and waiting 😄

hallow acorn
hallow acorn
burnt vapor
fading seal
burnt vapor
#

Also, I would assume intIcon should be shown if it's closed so this should depend on open

#

Unless the point is showing it until you interact with the fridge

burnt vapor
#

All you need to do now is remove the second SetActive and move the door depending on the state

#

And maybe rename the gameobject but this is more code style

fading seal
timber comet
burnt vapor
burnt vapor
#

The point is that having two is messy and this will not work properly

timber comet
burnt vapor
#

Like, what if you want it to open smoothly? Two gameobjects that appear and disappear do not work

#

Not to mention collission means you will be stuck inside the door if it opens, probably

hallow acorn
hallow acorn
safe radish
severe spear
#

I'm trying to make a movement system by myself and I got an error that I don't really understand saying that the expression '==' is invalid

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

public class movement : MonoBehaviour
{  
    //measured in unit per second
    private float jumpHeight = 7f;
    private float walkspeed = 5f;
    private float runspeed = 10f;
    void Update()
    {
        float verticalInput = Input.GetAxis("vertical");
        float horizontalInput = Input.GetAxis("horizontal");

        if (Input.GetKeyDown(KeyCode.Space)) == true;
         transform.position = transform.position + new Vector3(verticalInput * jumpHeight * Time.deltaTime, 0, 0);

        Debug.Log(transform.position);
    }
}```
modest dust
#

You misplaced your closing )

#

Should go after true

languid spire
#

this
if (Input.GetKeyDown(KeyCode.Space)) == true;
is invalid C#

modest dust
#

And besides that, == true is redundant either way

eager spindle
modest dust
#

if (Input.GetKeyDown(KeyCode.Space)) is already enough

merry osprey
#

any of you guys know where i can find unity version 2017.4.9f1

modest dust
#

Probably in the archive

severe spear
merry osprey
fading seal
# burnt vapor No, you have a single one that you change the location and rotation of
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class fridgeScript : MonoBehaviour
{
    public GameObject inticon, fridge, door;
    bool open = true;
    
    void Start(){
        door.SetActive(false);
    }
    void OnTriggerStay(Collider other){
        if(other.CompareTag("MainCamera")){
            inticon.SetActive(true);
            if(Input.GetKey(KeyCode.E)){
                fridge.SetActive(true);
                door.SetActive(!open);
                open = !open;
                door.transform.Rotate(new Vector3(-90, 0, -90));
                inticon.SetActive(false);
            }
        }
    }
    void OnTriggerExit(Collider other){
        if(other.CompareTag("MainCamera")){
            inticon.SetActive(false);
        }
    }
}``` is this right
modest dust
merry osprey
#

its okay

burnt vapor
#

Right now you always rotate it the same way

#

Also, try it and see. Half the debugging is about seeing what it does

fading seal
#

this kinda happened

fading seal
burnt vapor
#

It just opens, then it opens again, and again

fading seal
# burnt vapor Yes, how else do you close it?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class fridgeScript : MonoBehaviour
{
    public GameObject inticon, fridge, door;
    bool open = true;
    
    void Start(){
        door.SetActive(false);
    }
    void OnTriggerStay(Collider other){
        if(other.CompareTag("MainCamera")){
            inticon.SetActive(true);
            if(Input.GetKey(KeyCode.E)){
                fridge.SetActive(true);
                door.SetActive(!open);
                open = !open;
                door.transform.Rotate(new Vector3(-90, 0, -90));
                inticon.SetActive(false);
                if(open == true){
                    door.transform.Rotate(new Vector3(-90, 0, 0));
                }
            }
        }
    }
    void OnTriggerExit(Collider other){
        if(other.CompareTag("MainCamera")){
            inticon.SetActive(false);
        }
    }
}``` this is the code idk if its right but the door keeps disappearing
#

oh wait

fading seal
full kite
#

I want to be like this, and instead of that Its looking like this @eager spindle

eager spindle
#

or the other way round

full kite
eager spindle
#

carpet a child image of the dog

full kite
#

but lets say i didnt have that solution. Why do I anchor it, put some positions throughtout the script and its still moving through ui

#

this is my main question

#

@eager spindle this was the code to setparent a gameobject?

myGameObject.transform.parent = carpet1.transform;

burnt vapor
#

it's either the open rotation or the closed rotation

#

Now it's either the closed rotation or the closed+open rotation

fading seal
burnt vapor
weak talon
#

hello, i am making fps shooter and my camera is jittery

the player is a parent to the camera and when i move the camera (like rotation) it is fine but only when i start moving and rotating the camera the camera movement is very jittery

the rigidbody is interpolate, movement is in fixedUpdate as it is rigidbody movement, and cameramovement is in lateupdate
please help (tell me if you need to see any code)

safe radish
fading seal
# burnt vapor Instead of an if statement make an if-else statement
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class fridgeScript : MonoBehaviour
{
    public GameObject inticon, fridge, door;
    bool open = true;
    
    void Start(){
        door.SetActive(true);
    }
    void OnTriggerStay(Collider other){
        if(other.CompareTag("MainCamera")){
            inticon.SetActive(true);
            if(Input.GetKey(KeyCode.E)){
                fridge.SetActive(true);
                door.SetActive(!open);
                door.SetActive(true);
                open = !open;
                door.transform.Rotate(new Vector3(-90, 0, 0));
                if (open == true) {
                    door.transform.Rotate(new Vector3(-90, 0, 0));
                }
                else{
                    door.transform.Rotate(new Vector3(-90, 0, -90));
                }
                inticon.SetActive(false);
            }
        }
    }
    void OnTriggerExit(Collider other){
        if(other.CompareTag("MainCamera")){
            inticon.SetActive(false);
        }
    }
}``` is this right
burnt vapor
#

How often do I need to mention this

burnt vapor
#

I understand you lack basic knowledge of C# but surely you notice these mistakes?

#

Especially after I mentioned them three times

random cave
#
screenPosition = Input.mousePosition;
            worldPosition = cam2.ScreenToWorldPoint(screenPosition);
            worldPosition.y = 1000f;```
>
```cs
if (Input.GetMouseButtonDown (0)) 
            { 
                box.transform.position = worldPosition;
            }```
Why is this not precisely on where the mouse is? its off by this much [Check ss below]
weak talon
#

hello, i am making fps shooter and my camera is jittery

the player is a parent to the camera and when i move the camera (like rotation) it is fine but only when i start moving and rotating the camera the camera movement is very jittery

the rigidbody is interpolate, movement is in fixedUpdate as it is rigidbody movement, and cameramovement is in lateupdate
please help (tell me if you need to see any code)

burnt vapor
#

learn some basic c# before you undertake a game at any scale

burnt vapor
#

Hi, can you please send a proper screenshot? Or copy paste the full error in here.

full kite
#

myGameObject.transform.parent = carpet1.gameObject.transform;

#

this is the line of code to set the parent of "myGameObject" to "carpet1" ?

random cave
#

Please format it into something else other than jxr

trail heart
#

How do you even end up with a jxr file

silk night
#

If you are on win 11 press WIN + Shift + S, mark the area and just do ctrl + v here

weak talon
# random cave Try without interpolate

when i have the rigidbody to 'none' the camera movement is fixed but the movement of the player is a bit jittery
and with extrapolate it doesnt change anything

silk night
weak talon
silk night
#

oh i apparently cant read. What methods do you use to move the player?

#

also if you disable the camera movement itself and just keep the player movement enabled (moving the camera through parenting), does it still jitter?

weak talon
silk night
#

so there is no code affecting camera position right now? only the player being moved (and the camera following through parenting) and the camera still jitters?

silk night
weak talon
random cave
#

Perspective does not work

silk night
#

I think the screentoworld if for perspective, i remember having a problem but I am not 100% on that statement

silk night
random cave
#

Bruhh wellif I am in perspective mode the world positio isnt changed

weak talon
#

rb.addforce

weak talon
silk night
#

wdym the other way around?

weak talon
#

when it is on interpolate the movement is fine but the camera is jittery when i rotate it like moving my mouse

silk night
random cave
silk night
#

if so you can create a plane in code, and on click send a ray to your mouse cursor from the camera which then intersects with your plane and gives you a point

random cave
#

aH

silk night
#

that just tells you the build failed, is there no other output?

silk night
lean sedge
#

I've created a canvas in which a panel with an image to become an inventory slot. When I add an image to it that's literally a square with a border I only see two sides of the border when running the game. Almost as if the camera is looking at my canvas from an angle.

languid spire
lean sedge
silk night
#

you can slice it to always show the border and resize the center

lean sedge
#

I must admit I forgot to resize this image now I think about it

silk night
#

you can just slice that image and have it any size you want

lean sedge
#

Sometimes the answer is so easy you'll never find it yourself

weak talon
silk night
#

the border will stay the same size and the center will stretch

silk night
lean sedge
#

I did slice it however

#

so thats kinda odd

silk night
#

is your image component set to that type?

#

it was called sliced too i think

weak talon
silk night
lean sedge
#

Yea it is set to sliced, and I set the borders I never pressed slice tho

weak talon
silk night
silk night
# weak talon nope

ok good, sounded like that, one more thing, how do you rotate the camera, around the player (independently) or do you rotate the player rb?

tranquil scarab
#

https://gdl.space/ucurivegav.cs does anybody know why this happens? i have made this function for floor objects that can be bought. it is about the wave part in the buy function where it breaks. for some reason the refrence to the object that i want to instantiate is null??

languid spire
tranquil scarab
#

oh yeah srry forgot to add the screen. its on line 128 where the print is.

cosmic dagger
silk night
#

which line is 128 in your paste? hard too see without line annotations

languid spire
#

so hexagonPrefab is null

cosmic dagger
tranquil scarab
tranquil scarab
languid spire
tranquil scarab
#

also not null

#

so i dont get why this happens

cosmic dagger
languid spire
#

obviously what you are looking at is not what the code is pointing to. So debug it

languid spire
cosmic dagger
# tranquil scarab

is this the reference.prefab (the prefab within the reference SO?) hard to tell with small screenshots of the inspector. just send the entire inspector so we can see . . .

tranquil scarab
languid spire
#

I would guess that you are looking at 2 or more different objects. Add an instanceid to the debug

lean sedge
silk night
#

check the compression then

languid spire
lean sedge
silk night
#

filter, sorry

#

set it to point

lean sedge
#

point no filter I think

silk night
#

whats your wrap mode?

lean sedge
#

clamp

silk night
#

nvm, doesnt matter

#

hmm weird then

lean sedge
#

Yea I dont get it lol

cosmic dagger
# tranquil scarab there u go

hexagon.prefab is assigned to refrence.prefab. we need to see the Refrence ScriptableObject inspector, not the Hexagon script component . . .

tranquil scarab
tranquil scarab
languid spire
silk night
lean sedge
#

Now it has borders on three sides

silk night
#

can you screenshot your slices and the result that you currently see?

tranquil scarab
#

oooohh i found it. whenever i call the BuyPlace function to the new hexagon the refrence isnt set yet. this confuses me tho because that means that the start isnt giving the refrence before the function is triggered?

lean sedge
silk night
#

yeah then your image has more pixels than you can show and as the border is pretty thin it gets omitted

cosmic dagger
tranquil scarab
#

yeah

lean sedge
#

I'll try enlarging the border

silk night
cosmic dagger
# tranquil scarab yeah

honestly, your hexagon prefab should be of type Hexagon instead of GameObject. you need access to the Hexagon script, not any field of GameObject . . .

tranquil scarab
cosmic dagger
#

also, where do you set the reference for the instantiated hex? you mentioned, "the refrence isnt set yet," . . .

cosmic dagger
#

this avoids calling GetComponent to grab the component reference . . .

tranquil scarab
tranquil scarab
lean sedge
silk night
#

and your pixels per unit (setting on the sprite)?

lean sedge
#

100

silk night
#

what happens if you change that value? play around with it a bit

lean sedge
#

It doesn't really get better, but must say making the border a bit bigger is already hella better

silk night
#

i mean it fixes your symptom but not the source

Oh, are you zoomed out in your editor game window maybe?

#

if you simulate a bigger window that it is able to display those symptoms might appear too 😄

lean sedge
#

Im not zoomed out in the game window

silk night
#

hmm weird 😄 my last try would be making a build to see if it still happens on fullscreen, last thing i can imagine is in-editor scaling fuckery

lean sedge
#

Think it did have to do with the scaling of the window

#

it was on free aspect

#

So I think it just did some weird things, on full screen 16:9 Im good

silk night
#

do you have a canvas scaler active?

#

if so that would be pretty normal to happen as your in-editor window is much smaller than your targeted resolution 😄

sudden pilot
#

guys how can ı random ınstantıate an object ın cırcle transform area?

cyan vortex
#

I wanted to say sorry to everyone for earlier as I really want to fix this issue because I've got a meeting for my new course on Monday.

broken cargo
cosmic dagger
sudden pilot
#

ı am looking on it now

cosmic dagger
#

You can also use that to write a method to instantiate between specific radii as well . . .

sudden pilot
#

ı mean can ı make higher or smth

charred spoke
#

Yes just multiply it by your desired radius

sudden pilot
#

like that right?

charred spoke
#

Yes

sudden pilot
#

okay

cosmic dagger
random cave
#
screenPosition = Input.mousePosition;
            worldPosition = cam2.ScreenToWorldPoint(screenPosition);
            worldPosition.y = 1000f;```
```cs
if (Input.GetMouseButtonDown (0)) 
            { 
                box.transform.position = worldPosition;    
            }```
Trying to move a box when I click (inside of a minimap), it works but it has this very weird offset can anybody help? Using orthographic view I heard this can do stuff to it but I have no idea
swift crag
#

you're working on an interactive map, right?

ionic zephyr
#

I have slots for the inventory which show the quantity and the sprite of the object but I also want to create slots that only show the name and other type of slots which only show the sprite, should I make only one component for the three or different components?

swift crag
#

I'm guessing your problem is that [0,0] on your screen does not correspond to [0,0,0] in the world

random cave
#

It works and everythng its just the offset

#

I want it to be precisely on the mouse

swift crag
#

If you can figure out where the bottom left and upper right corners of the map correspond to, it'd be easy enough to get the world position

random cave
#

I tried that but it didnt go well

swift crag
#

I'm not exactly sure how I'd handle this, though. Haven't implemented a map before.

#

You could stick down two empties in the world

#

line them up properly manually and you'll be good to go

random cave
#

Yes I did that

#

The dot was moving out of the screen

cosmic dagger
swift crag
#

I would give that another try. Show me the code you're using to find the world position if it's not working

ionic zephyr
random cave
cosmic dagger
ionic zephyr
cosmic dagger
#

yep. try one method. if that doesn't work, try the other . . .

random cave
vast moat
#

could anyone help me write a piece of code that makes an object rotate towards where my mouse is in a top down 3d game? i've tried so many things but most of them just end up pointing towards the ground or rotating in a really funky way that isnt a smooth circle around my character. thanks!

wintry quarry
random cave
wintry quarry
random cave
#

Its a minimap trying to convert an image to real coords

wintry quarry
#

Looks like you're directly using screenPosition

#

which has a z distance of 0

random cave
random cave
wintry quarry
#

See the diagram here

#

Honestly I prefer to use Plane.Raycast

#

it's much easier to think about

random cave
#

Ok wait

#
Vector2 localMousePosition;

                RectTransformUtility.ScreenPointToLocalPointInRectangle(Minima, Input.mousePosition, null, out localMousePosition);

                movePoint2 = new Vector3 (localMousePosition.x, localMousePosition.y, 10);```
Would the plane raycast work with this
#

This is how I move it

silk night
wintry quarry
random cave
cosmic dagger
random cave
#

How would I do everything in world space if I need to use a red dot first thats in screen space

swift crag
random cave
wintry quarry
random cave
#

Thats like moving what I have rn to world space

wintry quarry
#

The minimap is a visual representation of world space objects, no?

random cave
#

Yes

#

No I understand what you mean

#

But I also have o idea how to make it back to canvas

#

I also tried to do that earlier but it had a weird offset

wintry quarry
swift crag
#

Or is it just a static image?

swift crag
#

Okay, then it's a lot simpler

random cave
#

It is a real camera

#

So you guys think I should use the plane raycast?

random cave
#

I clicked inside the blue circle

#

Its not the same everywhere

#
Ray ray = cam2.ScreenPointToRay(screenPosition);

                if (plane.Raycast(ray, out float distance))
                {
                    worldPosition = ray.GetPoint(distance);
                }```
#

It also changes if I increase the fov or not

#

If I use perspective still bugged

swift crag
#

Is cam2 rendering to your entire screen, or is it rendering to a RenderTexture that you then display in a UI?

random cave
#

Yes render texture

swift crag
#

Then cam2.ScreenPointToRay is not correct. You have to figure out where you clicked inside whatever is displaying the RenderTexture.

wintry quarry
random cave
swift crag
random cave
#

I already have a script that shows me if Im hovering over the ui

#

Then I just check for mouse input

swift crag
#

The camera has no idea how you're displaying its output. It can't possibly know the size or position of your RawImage (or whatever you're using to show the render texture)

#

So you can't just ask it to turn a screen point into a world point

random cave
#

Ah

swift crag
#

You figure out where inside the RawImage you clicked. That gives you a viewport position for the camera. You can then convert that into a world-space ray

random cave
wintry quarry
random cave
#

Well yes but I dont understand why would it need player camera but okl ol

wintry quarry
swift crag
#

actually, if the UI is an overlay canvas, you should pass null there

random cave
#

Oh that makes sense

swift crag
#

i bumped into this recently

wintry quarry
#

it's important

random cave
#

Ok ill go try that

#

Box is not moving

#
bool clickedInMinimap = RectTransformUtility.ScreenPointToLocalPointInRectangle(Minima, Input.mousePosition, null, out Vector2 viewportPoint);
                if (clickedInMinimap) 
                {
                    Ray r = cam.ViewportPointToRay(viewportPoint);
                    if (plane.Raycast(r, out float distance))
                    {
                        worldPosition = ray.GetPoint(distance);
                    }
                }
                box.transform.position = worldPosition;```
swift crag
#

well, you'd better do some debugging then

#

check each value you get

random cave
#

Gotcha

bold swallow
#

is there really no way to multiply a bool with a float?

swift crag
#

Why would there be?

#

You also can't multiply a GameObject with a string

bold swallow
#

well a bool is either 0 or 1

swift crag
#

Incorrect. A bool is either true or false.

#

The internal representation is irrelevant.

swift crag
#

Now, if you want to pick between two values using a bool, you can use the conditional operator

#
cond ? foo : 0;
bold swallow
#

All right

radiant frigate
#

can someone help me understand input system callbacks and how to use them? been reading docs and watching yt tutorials for 2 hours and dont understand why or how the " += (InputAction.CallBackContext) " is used

swift crag
#
System.Func<int, int> add1 = (int x) => x + 1;

This syntax is used to create an anonymous function. It's a function with no name.

#

(int x) => x + 1; is an anonymous function that takes one argument (an int) and returns an int

#

InputAction has a few events on it, like performed and canceled

#

You can subscribe to an event by adding your function to it.

bold swallow
swift crag
#
someAction.performed += (InputAction.CallbackContext context) => { /* multiple lines of code can go here */ };
#

you can simplify that down to just

#

(context) => { /* ... */ }

#

since the type of the argument can be inferred

#

or even just context => { /* ... */ }

#

if there's only one argument, you don't need the parentheses

radiant frigate
#

inferred?

#

what does that mean?

swift crag
#

the compiler figures it out from context

#
var x = 1;
#

the type of x is int here

radiant frigate
#

alright

#

im going to read it and tell you if i need some more assist, am i able to ping you in that case ?

swift crag
#

whatever code is inside the braces gets executed

#

note that you can't unsubscribe from the event if you do this

#

even if you use -= with an identical-looking anonymous function, that's a different anonymous function, so it won't work

radiant frigate
#

but i can -= right?

swift crag
#

I generally do this:

radiant frigate
#

ohhh

#

since its anonymous?

swift crag
#

not because it's anonymous, but because two identical looking anonymous functions are still different

#

just like two functions that have the same name but are in different classes

radiant frigate
#

i understand

swift crag
# swift crag I generally do this:
void OnEnable() {
  action.performed += HandleAction;
}

void OnDisable() {
  action.performed -= HandleAction;
}

void HandleAction(InputAction.CallbackContext ctx) {
  // ...
}
radiant frigate
#

why the ctx?

#

its just the name right?

swift crag
#

ctx is the name I gave to the parameter.

#

It could be named anything.

radiant frigate
#

ty for the help im kind of new to unity and programming

swift crag
#

I use ctx because it's short. context is also reasonable

#

Or even _, if you don't care about the parameter at all

#

That tells the compiler it's just "filler"

#

you can't have no parameters at all, because then HandleAction would take the wrong number of arguments.

radiant frigate
#

okay let me try to read all again and see if i understand

radiant frigate
#

what im understanding is that whenever an event happens i can susbscribe a function by adding it, InputAction has events like performed, started or canceled, but i dont know exactly how to add the function

swift crag
swift crag
#

Every time the event is invoked, HandleAction will run

random cave
radiant frigate
#

!code

eternal falconBOT
random cave
#

If I move the camera tho, the coords are right

random cave
radiant frigate
#

important lines are from 43 to 51

swift crag
#

You should also unsubscribe in OnDisable.

#

But yes, that sounds fine otherwise

radiant frigate
#

okay so let me understand it again, whenever the performed event happens it will automatically start the dash function

polar acorn
radiant frigate
#

without a need to tell it via code

swift crag
#

Every function that has been subscribed to the performed event will be executed whenever the performed event is invoked.

polar acorn
radiant frigate
#

okay

#

ty very much

#

and to subscribe to it i just need to add the (InputAction.CallBackContext ctx) after the name of the function

swift crag
#

You need a function that takes one argument

radiant frigate
#

so it doesnt throw an error

swift crag
#

The argument must be an InputAction.CallbackContext

#

That's it.

radiant frigate
#

okay

#

another question if i may

swift crag
#

The function can be anonymous, or it can be a method.

radiant frigate
#

why does it work with that argument but not with an int for example

swift crag
#

because you can't put a round peg in a square hole

radiant frigate
#

ik it sounds dumb i just want to interiorize it

swift crag
#

performed wants a function that takes exactly one argument

#

the argument must have the correct type

radiant frigate
#

okay let me formulate it again i think i missexplained myself

#

why is it inputAction.CallBackContext

#

what does it do

radiant frigate
#

ty!

swift crag
#

InputAction.CallbackContext is the type of thing the function is given.

#

CallbackContext is defined inside of InputAction

#

hence you refer to it as InputAction.CallbackContext

#

it's a nested type

#
public class InputAction {
  public struct CallbackContext {
  
  }
}
radiant frigate
#

okay i think i understand now

#

thank you!

random cave
#

Imma keep researchng ty tho

swift crag
random cave
#

What

#

Wdym special

swift crag
#

because thats just the center of the camera with no mouse

polar acorn
random cave
#

Yes exactly

#

Whats what im saying

polar acorn
#

So why can't you use it

swift crag
#

No, what you said is that it doesn't work because there's no mouse involved

random cave
#

Because im using my mouse to point and click

random cave
polar acorn
swift crag
#

The function takes a positions whose values are in [0..1] and outputs a world position

#

RectTransformUtility.ScreenPointToLocalPointInRectangle figures out your local position in a RectTransform

polar acorn
swift crag
#

I think I see the problem, though.

polar acorn
#

If you can get a viewport point from your mouse, you can use that

swift crag
#

ScreenPointToLocalPointInRectangle gives you a local space position

#

That is not a normalized position inside the rectangle

#

which will have values in [0..1]

#

Show the actual values you're getting. We haven't seen those yet.

random cave
#

Now I need a rect

#

Brah

swift crag
#

well, you have a RectTransform...

wintry quarry
random cave
wintry quarry
#

Yes...

swift crag
#

It finds a local-space position

#

This is not a normalized position within the rect

random cave
swift crag
random cave
#

oh just add .rect....

#

I feel stupid

#

"Member 'Rect.PointToNormalized(Rect, Vector2)' cannot be accessed with an instance reference; qualify it with a type name instead",

swift crag
#

Pay attention to the page I linked.

#

public static Vector2 PointToNormalized(Rect rectangle, Vector2 point);

#

This is a static method.

#

You don't call it on a specific Rect

random cave
#

I dunno what static does expect that its always there

swift crag
#

static means that the member is part of the type, not part of a specific instance of the type

#
Foo myInstance = new Foo();
myInstance.Bar();

vs.

Foo.Bar();
random cave
#

Ah

swift crag
#

In this case, it would be very reasonable for this to be non-static

#

but it isn't 🤷

#

Returns the normalized coordinates cooresponding the the point.

#

great docstring

random cave
#

Yea its a bit frustrating sometimes these documents dont tell me how to apply them

swift crag
#

The function signature tells you everything you need to know, though.

random cave
#

Signature?

random cave
#

Ah

#

True

swift crag
#

It tells you the name and type of each parameter, as well as the type that gets returned

random cave
#

Yea its quite useful

#

After a bit of debugging the worldposition is 0 even tho the viewport normalized is fine, distance is fine, it gets fucked up in the raycast somewhere

swift crag
#

Show the actual values.

#

(and show your new code, including the debug.log lines)

random cave
#

ViewportPoint: (85.10, 98.09)
Normalized: (0.63, 0.65)
Distance: 19,999.99
World Position: (0, 0, 0)

#
bool clickedInMinimap = RectTransformUtility.ScreenPointToLocalPointInRectangle(Minima, Input.mousePosition, null, out Vector2 viewportPoint);
                Debug.Log("ViewportPoint: " + viewportPoint);
                Vector2 viewportPointNormalized = Rect.PointToNormalized(Minima.rect, viewportPoint);;
                Debug.Log("ViewportPointNormalized: " + viewportPointNormalized);
                
                if (clickedInMinimap) 
                {
                    Ray r = cam.ViewportPointToRay(viewportPointNormalized);
                    if (plane.Raycast(r, out float distance))
                    {
                        Debug.Log("Distance: " + distance);
                        worldPosition = ray.GetPoint(distance);
                    }
                }
                box.transform.position = worldPosition;
                Debug.Log("WORLD: " + worldPosition);```
swift crag
#

is cam the correct camera? I remember it being named cam2 last time you showed the code

#

This one should be the minimap camera.

random cave
#

Yes it is

swift crag
#

20,000 is a very large distance. Is the minimap camera just really far away from the ground?

random cave
#

I made cam2 the player cam

swift crag
#

I would use Debug.DrawLine to visualize this