#💻┃code-beginner

1 messages · Page 543 of 1

burnt vapor
#

Do they all explicitly set the state or do they just look at the state?

willow sand
#

theres 3 that control the sate like for example when it turns into the attack state and theres one that sets the target to attack and then theres one that set the attack output

astral falcon
#

There should be one source of truth about states. Other scripts just react to it. is that what you mean?

burnt vapor
#

Have you debugged these three with the log messaging or debugging I specified, and are you 100% sure that it definitely sets these animation states?

willow sand
#

you mean transitions?

willow shoal
#

Hi. quick question. I need a line of code, what add to this script for keep moving a player yValue position after click

using UnityEngine;

public class aabbaa1 : MonoBehaviour
{
    float xValue = 0f;
    float yValue = 0.1f;
    float zValue = 0f;
    [SerializeField] bool moveup;
    
    void Start()
    {
        moveup = false;
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.E))
        {
            transform.Translate(xValue, yValue = 0.1f, zValue);
            moveup = true;
        }       
    }
}
frail hawk
#

just use Vector3.up

willow shoal
#

thanks i will try this

humble forum
#

hi i got a question

#
public class  TowerProjectiles : MonoBehaviour
{
    public GameObject projectilePrefab; 
    public Transform firePoint;         
    public float range = 5f;          
    public float fireRate = 1f;        

    private float fireCooldown = 0f;  
    private Transform target; 
    private LineRenderer lineRenderer;
    public bool showRangeInGame = true;
    ```
#

here i set the projectileprefab for the defense tower

#
using UnityEngine;
public class Projectile : MonoBehaviour
{
    public float speed = 10f;
    public int damage = 10;       
    private Transform target;     
    public void SetTarget(Transform newTarget)
    {
        target = newTarget;
    }

    void Update()
    {
        if (target == null)
        {
            Destroy(gameObject); 
            return;
        }
        Vector3 direction = target.position - transform.position;
        float distanceThisFrame = speed * Time.deltaTime;

        if (direction.magnitude <= distanceThisFrame)
        {
            HitTarget();
            return;
        }

        transform.Translate(direction.normalized * distanceThisFrame, Space.World);
        transform.LookAt(target);
    }
    
    private void HitTarget()
    {
       
        Enemy enemyManager = Object.FindFirstObjectByType<Enemy>();
        if (enemyManager != null)
        {
            foreach (var tempEnemy in enemyManager.GetTemporaryEnemies())
            {
                if (tempEnemy.spriteRenderer != null && 
                    Vector3.Distance(tempEnemy.spriteRenderer.transform.position, transform.position) < 0.5f)
                {
                    enemyManager.ApplyDamage(tempEnemy, damage); 
                }
            }
        }
        Destroy(gameObject);
    }
}
#

the code works but want the prefab to be visible

copper crest
#

Hey. i need help in something

#

how can i make a players material change with a button?

#

what script should i add? i have no idea what lines to use.

copper crest
#

urm i know that

#

what command should i use bruh

burnt vapor
#

That first link is pretty interesting

#

Somebody with the same question. They just didn't know how to iterate between them

#

Want to know how to easily do that?

green flame
#

Hello! When I try to change the current scene from my game I have the error message:
"Scene 'MainMenu' couldn't be loaded because it has not been added to the active build profile or shared scene list or the AssetBundle has not been loaded.
To add a scene to the active build profile or shared scene list use the menu File->Build Profiles"

I'm using this method: "SceneManager.LoadScene("MainMenu");"

#

My projet look like this

#

I tried to add the MainMenu scene here but I don't see the MainMenu scene anywhere

#

Someone can help me please ^^ ?

runic lance
green flame
#

Oh god thx! So easy I was 1hour on this thing xD Sometimes unity UI is a bit hard to understand ^^

runic lance
#

yeah, this thing is specially strange to use, no idea why you can't simply select scenes there

astral falcon
mint surge
#

Uhh I got a map from the asset store and I don't know how to add the whole map to the game, it's now in my project thing

#

Why are the trees pink now 😭

flat sphinx
#

whats the syntax for
foreach(var thing in [x, y])

tawdry quest
# mint surge

The map wasnt made for your rendering pipeline, you need to convert the materials

flat sphinx
#

cuz that one doesnt work

tawdry quest
#

Foreach is different

mint surge
flat sphinx
burnt vapor
#

It's unclear what you want here, please be more specific

languid spire
burnt vapor
#

I doubt my code even works

#

No, definitely doesn't

languid spire
#

and some C# basics lessons would seem to be in order

burnt vapor
#

If the point is iterating a joined collection, then you probably need

foreach(var thing in x.Concat(y))
flat sphinx
burnt vapor
#

Don't ask how to do the solution, ask about the actual issue

#

From this it seems like you might want to invoke behaviour based on if you work with an even or odd number, but I doubt it

languid spire
#

do you mean
GameObject[] gos = new GameObject[2];
...
foreach (GameObject thing in gos) {
// Do Stuff
}

flat sphinx
#

why do i bother

burnt vapor
#

Don't know what you want us to say

#

Explain the issue instead of relying on AI

#

What are you trying to do that requires this?

languid spire
flat sphinx
#
foreach(var thing in new[]{current_board.base_board, ball})
    yeet_up(thing)
#

is what i needed

verbal dome
#

Are you actually using it for just 2 elements or are there more?

flat sphinx
#

and now i have it

languid spire
#

and here
GameObject[] gos = new GameObject[2];
it's already there which if you are iterating over it is where it should be in the first place instead of creating an array on the fly

flat sphinx
burnt vapor
#

I don't see why you would iterate two hardcoded elements instead of just calling yeet_up twice

verbal dome
#

Alright. Tbh I never thought of constructing an array in the foreach loop's header

burnt vapor
#

But as long as you send tiny snippets of code and AI I don't think it really matters anyway

flat sphinx
#

for(var/thing in (x, y))

burnt vapor
#

That's a tuple, though

flat sphinx
#

its a list

burnt vapor
#

() makes a tuple, [] makes a list

flat sphinx
#

not python

#

there arr only lists

burnt vapor
#

Regardless () would make a tuple

flat sphinx
#

even assocs are lists

burnt vapor
#

Even in C# it would

#

Just fyi, because even your code doesn't do that

#

Modern .NET does allow [] to define collections

#

But I still don't see why you bother allocating an array for two known elements when you can just call a method on them directly

#

I'd love to help if you actually shared code

flat sphinx
#

somehow

burnt vapor
#

Well, explain the issue

#

Why do you need this?

#

The current code looks like overcomplication but I assume the point is for something bigger

mint surge
#

I added a pipeline and converted but some parts are still not rendered while some are, idk how to do it welp

verbal dome
#

Show the material of one of the pink objects

swift crag
#

You need to select one of the objects with a renderer on it

#

They should all be children of this BLD_Bridge_A object

#

Then open its "Materials" list and double click on a material

mint surge
#

Well this is one

#

Wrong one

#

Done

flat sphinx
#

whats the non-blocking version of thread.sleep()

swift crag
#

what are you trying to actually do?

flat sphinx
#

need to wait some seconds for particles to finish and sleeping pauses the particles too

swift crag
#

you can use a coroutine to perform an action after a delay

flat sphinx
#

no they dont return a promise

swift crag
#

notably, you can yield a WaitForSeconds

flat sphinx
#

thanks

humble forum
#
using UnityEngine;
public class Projectile : MonoBehaviour
{
    public float speed = 10f;
    public int damage = 10;       
    private Transform target;     
    public void SetTarget(Transform newTarget)
    {
        target = newTarget;
    }

    void Update()
    {
        if (target == null)
        {
            Destroy(gameObject); 
            return;
        }
        Vector3 direction = target.position - transform.position;
        float distanceThisFrame = speed * Time.deltaTime;

        if (direction.magnitude <= distanceThisFrame)
        {
            HitTarget();
            return;
        }

        transform.Translate(direction.normalized * distanceThisFrame, Space.World);
        transform.LookAt(target);
    }
    
    private void HitTarget()
    {
       
        Enemy enemyManager = Object.FindFirstObjectByType<Enemy>();
        if (enemyManager != null)
        {
            foreach (var tempEnemy in enemyManager.GetTemporaryEnemies())
            {
                if (tempEnemy.spriteRenderer != null && 
                    Vector3.Distance(tempEnemy.spriteRenderer.transform.position, transform.position) < 0.5f)
                {
                    enemyManager.ApplyDamage(tempEnemy, damage); 
                }
            }
        }
        Destroy(gameObject);
    }
}
#
public class  TowerProjectiles : MonoBehaviour
{
    public GameObject projectilePrefab; 
    public Transform firePoint;         
    public float range = 5f;          
    public float fireRate = 1f;        

    private float fireCooldown = 0f;  
    private Transform target; 
    private LineRenderer lineRenderer;
    public bool showRangeInGame = true;
    ```
#

the tower handles the spawnpoint and should handle the prefab where the projectile script is bind too but can t get it working to see the projectile in the game itself😅

#

like the connection between those 2 files isn t great but dunno how to fix it

wintry quarry
#

Using Enemy enemyManager = Object.FindFirstObjectByType<Enemy>(); doesn't make a lot of sense

#

what if there is more than one enemy?

#

Also why would something with an Enemy script on it be an "Enemy manager"?

#

Wouldn't that be a completely different script?

wintry quarry
#

I would expect Enemy to be a single individual enemy

wintry quarry
#

Why don't you just use the Target?

humble forum
#

red lines are just debug lines for the range of the towers 🙂

humble forum
# humble forum

biggest bug for me right now is making the prefab appear i assigned

wintry quarry
wintry quarry
#

which it seems like you might have

#

which script(s) are on the enemies?
What does the Enemy script actually do?

swift crag
#

in which case you desperately need to fix the names of these classes

wintry quarry
#

It seems more like something that manages enemies

humble forum
wintry quarry
#

but that's not what the code will do, unless Enemy does not actually represent an enemy

humble forum
wintry quarry
#

And that object has... which scripts on it

swift crag
#

Enemy is definitely not an enemy, yeah

humble forum
#

and enemy wich does the rest with the enemy

swift crag
#

it has a list of "temporary enemies"

#

This thing needs to be renamed to EnemyManager or something similar

humble forum
swift crag
#

"both"?

humble forum
#

temporary and then normal enemy in that script

#

but what has that to do with the fireball projectile? cuz my naming convention might be cursed but the rest works?

wintry quarry
#

this is not correct in a 2D game

#

in a 2D game this is going to make the sprite rotate like in Paper Mario

#

and be invisible because you're looking at it on the impossibly thin paper side

#

to rotate it towards the target you would just do this:
transform.right = direction;

swift crag
#

LookAt is similar to transform.forward = target

#

but the "forward" direction in 2D points into the screen

humble forum
#

like this sorry im a bit confused

distant robin
#

hi can someone help me? i've made this full body fps by using fps controller by unity, changing the capsule with a 3d model from mixamo and adding triggers to the code for animation. i've attached the main camera to the head of the 3d model, apart from the eccesive head bobbing, my character always go towards right, (probably because of the animation), even if im just pressing w (like in this footage) can someone help me please? thanks

swift crag
#

ah, target is another Transform

#

you need a direction to the target transform

#

such as...

#
target.position - transform.position;
#

and then you need to set transform.right, not transform.forward

wintry quarry
#

transform.right = direction;

#

you already HAVE the direction variable

#

There's a reason I wrote direction and not target

swift crag
humble forum
#

but needs to be 2d right?

wintry quarry
#

It's already 2D

#

what do you mean

humble forum
wintry quarry
#

It doesn't matter

#

What I wrote is what you want

humble forum
#

like this?

swift crag
#

you still call LookAt

wintry quarry
#

READ WHAT I WROTE

humble forum
wintry quarry
humble forum
wintry quarry
#

no you don't

#

You have this

#

that's not the same

humble forum
distant robin
#

it was the root motion option

wintry quarry
#

you could have left it where it was

rich adder
#

LookAt was literally overwritting anything you wrote above with that. transform.right = becomes useless

wintry quarry
#

because if it's above, you will get an error when it's too close

#

the position in the code of where LookAt was is fine, but LookAt was wrong

humble forum
#

so what could be wrong no with the prefab not visible in the game?

wintry quarry
#

If it's still not visible you need to investigate further. Run the game and pause it and look at the inspectors of the objects and see what's wrong.

#

The projectile could be behind another sprite for example

#

But without seeing your project it's hard for us to say based on code alone. We need to see the scene setup.

wintry quarry
humble forum
# humble forum

bind the fireball projectile to the tower and that has its own script

wintry quarry
#

That doesn't answer the question

#

We want to see the SpriteRenderer

humble forum
vocal wharf
#

I'm making a 2d endless runner game (totally not a google dino clone) and I have the script set the high score to the current score if the current score > the previous high score. The only problem with this is that I use ```cs
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);

 to restart the game after I die and this resets my high score to 0. Is there any way to preserve this integer even when resetting the scene or am I gonna have to figure out a new way to restart the game?
Here is the relevant piece of code in case it's needed:
```cs
 if (collision2D.gameObject.CompareTag("Obstacle"))
        {
            Time.timeScale = 0;
            deathScreen.SetActive(true);
            finalScore.text = "Score: " + currentScore;
            if (currentScore > currentHighScore)
            {
                currentHighScore = currentScore;
                highScore.text = "High Score: " + currentHighScore;
            }
wintry quarry
#

But I suspect you do have one

#

it's probably just on a child object inside the prefab

humble forum
vocal wharf
wintry quarry
# humble forum

You need to pay attention to the sorting layers and order in layers of all your 2D sprites. That is how the drawing order is determined

flat sphinx
#

how do i yeet an obj

wintry quarry
#

if they're all on Default and 0 then it is just random which will draw on top

flat sphinx
#

i wanna animate some objects accelerating along an axis

humble forum
verbal dome
flat sphinx
verbal dome
#

You could use an actual animation or just modify the object's transform.position

humble forum
#

center to pivot and changing order layer to 5 didn t seem to matter tested both aside from eachother

rich adder
#

you also can do some Tweening @flat sphinx
(just interpolating position)

flat sphinx
#

as for animatinos idk how they work

verbal dome
#

You could simply have a float speed, every frame use speed = Mathf.MoveTowards(speed, targetSpeed, delta) to change the speed (accelerate), and move the transform to some direction multiplied by speed

#

Mathf.SmoothDamp is also a decent option depending on what you need

#

(Or Vector3.SmoothDamp)

supple oar
#

Hello guys, first time here! Just made a 2D movement system based on the player following a circle, but I am trying do find a way for the player to "dash" towards the circle 🤔. I have a tiny video of the game for anyone willing to help 😄

eternal falconBOT
rich adder
#

also dash can either be based on distance, time or both..

humble forum
#

navarone do you know why the fireball pixels don t spaen on my screen? blushie

rich adder
humble forum
verbal dome
humble forum
#

bruh it even moves perfectly towards the target just not visible

humble forum
rich adder
vocal wharf
humble forum
#

but it put it on 5

rich adder
#

make sure the order in layer is high enough

humble forum
rich adder
#

looks like the child fireball is very far from the parent

#

aka the visuals are wayyy further than parent moving

humble forum
rich adder
# humble forum where can i find that?

the move Tool in unity (W key ). when you show gameobjects so we can see the pivots but looks like child is way far, look at the position, it should be 0,0,0 from parent

vocal wharf
humble forum
#

first pic was the child

rich adder
humble forum
#

but the parent should also be 0 0 0 or only the child?

rich adder
#

the parent can also be 0,0,0 doesn't matter, that gets assigned when you do Instantiate anyway

#

the child is the main importance, it should not be that far away from parent, especially if its the visuals

humble forum
#

but the speed very low so visible but seem very small lol

rich adder
humble forum
#

is scaling ok or is that bad?

rich adder
#

you should probably turn off compression/filtering on sprite

#

looks bad on pixel art

#

looks blury

humble forum
#

where can i find that?

rich adder
verbal dome
#

Inconsistent pixel size gives a really unprofessional look

humble forum
verbal dome
#

Yeah, well, you asked if it's ok or bad.

rich adder
#

you could potentially scale down and make it look nicer by "zooming" back in with the Pixel Perfect component

humble forum
#

doesn t seem to be a sprite?

umbral bough
#

Hey, I created json config for the unity gradient.
It works fine for the most part, but there is 1 small issue.
When I assign it to the vfx graph's gradient, it looks odd.
The issue is with the gradient mode.
As can be seen in the first picture, it's correctly loading the mode from config, here's the conversion code too:

        /// Implicit conversion to <see cref="Gradient"/>
        public static implicit operator Gradient(ConfigGradient g) => new()
        {
            alphaKeys = g.AlphaKeys.Select(key => (GradientAlphaKey)key).ToArray(),
            colorKeys = g.ColorKeys.Select(key => (GradientColorKey)key).ToArray(),
            mode      = g.Mode
        };

But when I assign it to the vfx gradient, even tho it shows Blend (Perceptual), it looks wrong.
Picture 2 is what it looks like when assigned, picture 3 is what it looks like when switched to something else and back to perceptual, basically how it should look like.
It's also not just a visual thing as it's applied to the vfx graph in the wrong way too.
Thanks in advance!

wintry quarry
#

Look into DDOL singletons

rich adder
humble forum
#

where is that then?

verbal dome
#

Timo im sure you can find the project view if you put some effort in

humble forum
#

but this is the project view right?

verbal dome
#

Yeah

#

Click the parent asset

#

That's where you can see the import settings

supple oar
humble forum
#

i see looks more pixelated

#

fixed it thank you 🙂

long jacinth
#
    {
        Hovering = false;
    }
    public void HoverOn()
    {   
        Debug.Log("1");
        Hovering = true;
    }

so i have this script where when a mouse hovers over a button it should make a bool true or false but well it isnt working for the bool but it is for the debug

rich adder
rich adder
long jacinth
rich adder
supple oar
rich adder
supple oar
#

So, the position of the triangle is already changed every frame, dont know how to apply a "dash movement" over that without screwing up the PlayerTriangle movement

#

About MovementCircle, im using it so the player speed doesnt add up while moving in more than one direction

long jacinth
rich adder
#

narrow down now which functions are calling it

long jacinth
rich adder
#

yes 99% usually is a user mistake when something not work as intended lol

long jacinth
#

i set up the event trigger wrong but know i fixed it

#

now ima see if its working

#

its working but now i will see how to make it do what i want it to do

supple oar
# rich adder show the actual code
using System.Collections.Generic;
using UnityEngine;

public class FollowScript : MonoBehaviour
{
    public GameObject Target;
    public GameObject dashTarget;
    public Vector2 dashPosition;
    float moveSpeed;
    public float Dis;
    Vector3 mousePosition;
    // Start is called before the first frame update
    void Start()
    {

    }

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

    void RotateTriangle()
    {
        mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        Vector2 direction = mousePosition - transform.position;

        transform.up = direction;
    }

    void MoveTriangle()
    {
        PlayerMovement cs = Target.GetComponent<PlayerMovement>();
        moveSpeed = cs.moveSpeed;
        transform.position = Vector2.MoveTowards(transform.position,Target.transform.position,(moveSpeed - 1) * Time.deltaTime);
        if (Input.GetKeyDown(KeyCode.Space) && ((Input.GetKey(KeyCode.W))||(Input.GetKey(KeyCode.A))||(Input.GetKey(KeyCode.S))||(Input.GetKey(KeyCode.D))))
        {
            dashPosition = dashTarget.transform.position;
            transform.position = dashPosition;
        }
    }
}```
rich adder
#

you need a bool / switch statement if you plan on taking over the movement to do a precise currentpos to dashPos

#

or maybe run it in a coroutine too

heavy knoll
#

Anyone know how i can stop the pipe from getting destroyed if my player has collided with something resulting in the game being over?
https://hatebin.com/zkeyyiypvm

rich adder
languid spire
rich adder
#

or just let the pipe destroy itself if it goes out of screen, timer isn't reliable

frail hawk
#

or wrap a gameover check around the Destroy command

languid spire
heavy knoll
heavy knoll
languid spire
rich adder
frail hawk
#

nah that wont work, he said he want to stop the destroy on game over. it could be that the camera is also stopped

rich adder
#

he doesnt need the timer to destroy in the first place

frail hawk
#

oh yeah than it makes sense!

rich adder
#

the pipe only destroying itself outside screen kills 2 problem in 1

silent falcon
#

Hi,I am using UI ToolKit and would like to ask how to set up Dialog to display at a resolution of 200 * 100 on a 412 * 917 screen? Just like the green area.UnityChanHuh

languid spire
#

which Is why I said Coroutine

frail hawk
#

yep i would also work with a distance check instead timer. it is just innacurate

heavy knoll
#

currently what im trying to do is just make a flappy bird like clone so its just my player jumping in place and the pipes spawn in on the right, move to the left and get destroyed. And if the player collides with anything it calls my gameover method in my GameManager script

rich adder
frail hawk
#

i knew you would say that lol.

#

either works

rich adder
#

timer is ok what if you decide to have pipes that speed up and slow down? now timer breaks

frail hawk
#

no , did not mean timer i mean distance check or viewport. timer is really inaccurate after a certain amount of time.

#

i wuold not rely on it.

heavy knoll
tulip nimbus
#

Generally asking, is there a significant benefit to using Arrays over Lists?

languid spire
rich adder
#

cache the camera probably

supple oar
# rich adder yeah you should not be teleproting it with transform.position = use a rigidbody...

Just Tried this

    {
        if (Input.GetKeyDown(KeyCode.Space) && ((Input.GetKey(KeyCode.W))||(Input.GetKey(KeyCode.A))||(Input.GetKey(KeyCode.S))||(Input.GetKey(KeyCode.D))))
        {
            //dashPosition = dashTarget.transform.position;
            //transform.position = dashPosition;
            horizontal =  dashTarget.transform.position.x;
            vertical = dashTarget.transform.position.y;
            myRigidbody2D.velocity = new Vector2(horizontal * moveSpeed, vertical * (moveSpeed + 50));
        }
        else  
        {
            PlayerMovement cs = Target.GetComponent<PlayerMovement>();
            moveSpeed = cs.moveSpeed;
            transform.position = Vector2.MoveTowards(transform.position,Target.transform.position,(moveSpeed - 1) * Time.deltaTime);
        }
    }
heavy knoll
supple oar
#

Just got
NullReferenceException: Object reference not set to an instance of an object
FollowScript.MoveTriangle () (at Assets/Scripts/FollowScript.cs:45)
FollowScript.Update () (at Assets/Scripts/FollowScript.cs:25)

languid spire
#

great and we know what line 45 is how?

heavy knoll
supple oar
languid spire
#

so myRigidbody2D is null

rich adder
#

would probably cache camera in update
private Camera cam;
void Awake() => cam = Camera.main

heavy knoll
#

and in the if statement do a check to see if the game is over?

rich adder
#

for moving

heavy knoll
untold raptor
#

guys i need serious help...my wheels keep running away and my bike floats away
idk what settings to show so please lmk
im also using wheel colliders

heavy knoll
verbal dome
untold raptor
#

thank you

verbal dome
#

And show related code too

vocal wharf
#

I'm trying to call a function from another script in the script that I'm currently coding. I referenced the gameObject that the other script is on, and I used .GetComponent<MyScript>().MyFunction(); to try to get the reference of the function in the other script but I just can't find a way to call that function. How do you do this?

rocky canyon
#

soo u used
theOtherObjectYouSaidYouReferenced.GetComponent<YourScript>().YourFunction();

#

that should would if the script is indeed on the other object... and has said function

#

and the OtherObject is indeed referenced

languid spire
rocky canyon
#

ahh like caching just the function for later

vocal wharf
rocky canyon
#

i misunderstood

#

myAction(); <-- just like that

verbal dome
#

Yeah if you don't put () you will get a reference to the method

#

With () you will call the method instead

rocky canyon
#

neat..TIL

cosmic dagger
rocky canyon
#

any reason u'd cache individual methods and not the entire class?

#

seems like more flexibility with the later

cosmic dagger
languid spire
rocky canyon
#

ohh makes sense 👍

cosmic dagger
#

possibly for callbacks . . .

languid spire
#

indeed

cosmic dagger
#

if you want its execution in line within code or after code from another method . . .

verbal dome
#

You also often see it when you subscribe to an event: cs SomeEvent += MethodToCallWhenEventIsRaised;Note how there's no () because you dont want to actually call/invoke it here

languid spire
#

it's great in, for example, a Coroutine if you want a callback at the end of the coroutine execution

rocky canyon
#
        private void DrawCenteredButton(string buttonName, System.Action onClick, bool enabled)
        {
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUI.enabled = enabled;
            if (GUILayout.Button(buttonName, buttonStyle))
            {
                onClick?.Invoke(); // <-- aye, i have done this before.. i just forgotten
            }
            GUI.enabled = true; // Re-enable GUI
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
        }
        #endregion```
vocal wharf
#

What if I just do this

if (collision2D.gameObject.CompareTag("Obstacle"))
{
    gameManager.GetComponent<GameManager>().Death();
}

to call the method when I hit an obstacle?

rocky canyon
#

whats gameManager at the beginning?

languid spire
#

sure, that works

vocal wharf
#

gameManager is a gameobject that has the GameManager script attached to it

#

names are a bit confusing ig

rocky canyon
#

oh.. u know u can assign the GameManager script instead right?

#

GameManager gameManager;
then gameManager.Death();

#

but thats only if its available to do so with

vocal wharf
#

I tried but it didn't let me drag the script in the inspector

rocky canyon
#

u drag a gameobject w/ the script attached to that slot

#

not the actual script

vocal wharf
#

oohh

#

ok it works now thanks

rocky canyon
#

then u can avoid using GetComponent calls

rocky canyon
vocal wharf
#

it's weird though, my death method works when I collide with an obstacle but the PointScored method doesn't work. 🤔
Script on player that detects if I pass through obstacle trigger:

 private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Obstacle"))
        {
            gameManager.PointScored();
        }
    }

script on GameManager object that is supposed to add points to the score:

 public void PointScored()
    {
        currentScore = currentScore + 1;
        currentScoreText.text = "Score: " + currentScore;
    }

currentScore is a public int that is supposed to be displayed in the score text (all the text objects and stuff are assigned in inspector)

#

my score counter on screen stays at zero even when clearing an obstacle

polar acorn
#

See if it's the value you expect

#

You might be overwriting the UI text with something else

vocal wharf
#

hmm PointScored method isn't even being called. I'll try debug logging some other stuff and tell you what I find

#

ok the player isn't detecting the obstacle triggers

#

all the obstacles have trigger colliders above them

rocky canyon
#

are they all tagged correctly as "Obstacle"

vocal wharf
#

yes

#

do you want the whole player script?

rocky canyon
#

it may help !code use an external paste bin site tho

eternal falconBOT
vocal wharf
#

it's basically just jumping, ground check, obstacle collision check and obstacle trigger check

#

DUDE I'M LITERALLY SO STUPID

#

I used OnTriggerEnter instead of OnTriggerEnter2D 😭

#

It works 😮‍💨

#

now I gotta figure out how to make my high score not reset when the scene is reloaded

cosmic dagger
#

how granular would any of you go when creating packages? i have separate packages:

  • Utils (extension methods)
  • Core (base/boiler-plate framework)
  • Timer (timer class for calling events during certain phases of a timer)

I have an ObjectPool (a group of scripts), and was going to create a separate package for it, but i'm curious if i should group it with the core framework and pile most, if not, everything into that package. what say y'all?

rocky canyon
plush zealot
#

Is there a library that adds a method to do something when the hierachy changes/ children or parents are added or removed?

rocky canyon
plush zealot
plush zealot
#

tysm

rocky canyon
#

only works in editor tho..

#

not sure what u'd do for runtime

plush zealot
#

I just want to resize a ui object when children are added/removed

#

what would I use for that?

rocky canyon
#

the code that adds or removes from the hiearchy could also trigger that

#

if ur talkin about just scaling UI when more UI objects are added.. theres stuff like LayoutGroups that u could use to automatically do that

stuck palm
#

I love when i get 40 errors after a code refactor and then i fix those 40 errors and then 20 more show up 😄

#

why dont they all just show up together?

rocky canyon
#

b/c some errors stop other errors from being found.

#

not until u fix some.. does it execute enough code to find the others

cosmic dagger
rocky canyon
#

im awful at it.. soo if u do figure out the "optimal" way to sort this stuff let me know 😅

cosmic dagger
rocky canyon
#

ur far too humble

plush zealot
rocky canyon
#

ya, id use a vertical layout group for that

#

it'll automatically resize it however u need

plush zealot
#

ok and it doesnt inerfere with scrollrect?

rocky canyon
#

ohh.. that i dont know.. i think they can work in tandem. but not sure what all that involvs

cosmic dagger
plush zealot
#

alright imma try it and if it doesnt work ill come back :) thx again @rocky canyon

cosmic dagger
plush zealot
#

AAAAAAAAAAA

cosmic dagger
rocky canyon
#

ya, bet u got to do some nesting magic

#

cant have two types of scalars on the same object

rocky canyon
#

im bad at dynamic UI.. me and CSS fight daily

plush zealot
#

how does csf work excactly?

rocky canyon
#

no clue.. @cosmic dagger any thoughts?

plush zealot
rocky canyon
#

using UnityEditor; i believe

polar acorn
#

I've never actually fully understood how those interact

plush zealot
#

this doesnt work in c#? :<

rocky canyon
#

whats up with the asterisks?

plush zealot
#

in java it auto imports every sub library if you do
import Library.*;

rocky canyon
#

soo its probably use a utility type thing

plush zealot
#

this worked

rocky canyon
#

ya, thats another one to i forgot to mention ^

short hazel
#

In C# when you use a namespace, all the types in it are available to you, so it's equivalent to Java's *

magic panther
#

Yall why is the .point of my RaycastHit2D always slightly off? Like, when I BoxCast onto a collider, for some reason, the collision point is never the position of the collider combined with it's extents?

short hazel
rocky canyon
#

if u want u can clamp it to the nearest int

#

or decimal place if u wish

magic panther
#

damn

#

what's the best way to go about this

#

In a line like this (just in case) RaycastHit2D[] hitObjects = Physics2D.BoxCastAll(startPos, boxCollider.size, 0, direction, distance * Time.deltaTime);

supple sand
magic panther
#

this might be it

#

lemme check

supple sand
#

You only want to cast it a total distance that scales with frame rate?

#

Low frame rate = cast longer, fast frame rate = cast shorter

magic panther
#

no, but this was a minor issue, so thanks

#

but this is a major issue

supple sand
#

Whats an issue with that

magic panther
#

even with such tiny inaccuracies, you can get stuck in walls and floors

supple sand
#

You tested that hypothesis or you are assuming/ guessing?

#

float comparisions are usually using epsiolon comparisons so its accounts for that tiny inaccuracy

plush zealot
#

when changing the size by dragging the lower end of the object in the editor it changes the height automatically. What's the ratio for that?
Or is there a method that adjusts it automatically if the object is resized, that I can use in a script?

supple sand
#

You can use Mathf.Approximately

supple sand
magic panther
#

it's very rare

#

but it occasionally happens

plush zealot
supple sand
magic panther
#

I could check if the position is exclusive within the boxcast

supple sand
magic panther
supple sand
magic panther
#

I added this line when checking on the x axis (flipped x and y on the y axis): withinBounds = hit.point.y < startPos.y + boxCollider.bounds.extents.y && hit.point.y > startPos.y - boxCollider.bounds.extents.y;

plush zealot
#

ty for the tip

magic panther
#

@supple sand thanks a lot for the help :)

plush zealot
#

whats the output for 0%2? is it also 0?

hybrid finch
#

hi is it possible to assign color to a raycast?

frail hawk
#

do you mean for testing, if so yes you can use Debug

cosmic dagger
magic panther
#

I have this freeze frame mechanic, but it's just awful all around. How do I make a proper one?

    public void TriggerFreeze(float duration) {
        StartCoroutine(Freeze(duration));
    }

    private IEnumerator Freeze(float duration) {
        Time.timeScale = 0f;

        yield return new WaitForSecondsRealtime(duration);

        Time.timeScale = 1f;
    }
hybrid finch
magic panther
frail hawk
#

yeah, we already answered.

hybrid finch
cosmic quail
#

cause I can't see any problems in this script

plush zealot
#

so I got the resizing to work but the y position is set to -290 because of the scroll rect and it doesn't let me change ithttps://streamable.com/wdno67

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

public class SizeAdapter : MonoBehaviour
{
    private void OnTransformChildrenChanged()
    {
        RectTransform rectTransform = GetComponent<RectTransform>();
        if (rectTransform.childCount % 2 == 0) rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, rectTransform.childCount / 2 * this.GetComponent<GridLayoutGroup>().cellSize.y + this.GetComponent<GridLayoutGroup>().spacing.y * (rectTransform.childCount / 2 - 1));
        else rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, (rectTransform.childCount + 1) / 2 * this.GetComponent<GridLayoutGroup>().cellSize.y + this.GetComponent<GridLayoutGroup>().spacing.y * ((rectTransform.childCount+1) / 2 - 1));
        rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, 0f);
    }
}```
this is the script right now and and the last line gets overwritten by the rect too

Watch "Project T - Deck Builder - Windows, Mac, Linux - Unity 2022.3.21f1 DX11 2024-12-13 20-46-24" on Streamable.

▶ Play video
#

any idea on what to change so it alligns the to the top left and doesnt move the first ones off screen?

magic panther
mint lion
#

if you want to slow down time then you'll need to change Time.timeScale to a value above 0

supple sand
plush zealot
#

its not :(

supple sand
#

Has a new github link i guess

white kite
#

Hi ! Sorry to disturb, but I'm trying to make my enemy spawner spawn enemies faster and faster, so I wrote something then wanted to test, but it didn't go as expected... (see the last picture)

I would like to make enemies appear faster and faster over time. But to prevent it from becoming exponential, I wanted to do it by making it stagnate at a certain speed stage, but it seems it didn't work ? The seconds I make the game play, there's just an infinite amount of enemy going down 😭

polar acorn
cosmic dagger
#

more than one of your if statements can be true, resulting in multiple instantiated objects . . .

#

also, its easier to read if you post all of your !code in a single file . . .

eternal falconBOT
white kite
#

Aaaah I see... sorry I'm really new to coding and Unity in general, so I don't understand everything yet...
And I'll keep that in mind for next time, sorry again !

frosty field
#

I know that its almost not readable and im really sorry for that but i was just testing something and i was wondering why doesnt it work, the script should change the color of the capsule to 1.0f and then when it hits 1.0f it changes slowly to 0.0f and again to 1.0f, but all it does is chaning the color to 1.0f and leaving it like that
https://hastebin.com/share/aconetonap.csharp

#

any advices would be usefull

languid spire
#

first thing first, never check a float for equality

frosty field
#

what do you mean?

languid spire
#

dont you know what equality means?

polar acorn
frosty field
#

why is that?

#

and how to compare using matf.approximately

languid spire
#

in your case >= 1.0f rather than == 1.0f

#

because floats are almost never exactly equal the value you think they are

polar acorn
#

You might end up with 0.99999999997 instead of 1

#

But also in your case, you should be checking for greater than 1, since you have no control over the increments and it's unlikely to even approximately hit 1 depending on framerate

frosty field
#

ohh

#

i changed the if's to <= and >= and it does work perfectly now

#

thanks a lot

frosty field
#

but now i know

west radish
pliant abyss
west radish
#

When are they going to invent sink

#

Sinking point numbers are the new floating point

pliant abyss
west radish
#

Goodbye int, say hello to outt

polar acorn
#

if you need more precision for pure mathematics, use doubles or decimal

pliant abyss
#

I'm not saying floating point numbers are useless.

#

Just maddeningly imprecise in certain cases.

thin stream
#

Hi! how do i make this image clickable in unity?

frosty hound
#

Seperate the clickable elements or use invisible buttons.

thin stream
#

alright but do i need to implemt it as a tile map or image?

pliant abyss
#

Splines

worthy horizon
#

I assume have some polygon game objects on each item you want clickable, and use that as triggers etc

thin stream
#

do i need polygon (just new in unity for 2 weeks)

rocky canyon
#

well it'd be hard to make certain areas of it clickable using squares or circles

thin stream
#

alright

cerulean bear
#

why does line 17 have an error

using UnityEngine;

public class oppSpawner : MonoBehaviour
{
    private int numOfOps = 5;
    private int[] ops = new int[5];
    private float[] opPositions = new float[5];
    public float startingPos = -4.43f;
    public GameObject spawnable;
    private Vector3 spawnPos = new Vector3();
    private Vector3 spawnRotation = new Vector3(180, 0, 0);
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        for (int i = 0; i <= numOfOps; i++)
        {
            spawnPos = (startingPos, 4, 3);
            opPositions[i] = startingPos + i;
            ops[i] = i;
            GameObject spacesh = Instantiate(spawnable, spawnPos, Quaternion.Euler(spawnRotation));
        }
    }
    // Update is called once per frame
    void Update()
    {

    }
}
#

it's meant to spawn enemy spaceships in my 2d game (ignore how much I used the word op)

swift crag
#

you should always start by reading the error message..

cerulean bear
cerulean bear
polar acorn
# cerulean bear

Because spawnPos is a Vector 3, and (startingPos, 4, 3) is not

swift crag
#

spawnPos isn't even a vector3

#

it's a tuple again

thorny basalt
#

try new(x, y, z) or new Vector3(x, y, z) depending on context. :)

cerulean bear
swift crag
#

oh, I misread

#

yes, spawnPos is a Vector3; you're just trying to assign a tuple into it

cerulean bear
#

alr ty

spiral narwhal
#

Err, why are fields not serialised when I extend Unity's UI Button

polar acorn
#

Did you get UI.Button or UIElements.Button

#

and what fields are you trying to serialize

spiral narwhal
#

Just the normal UI buttons

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace DefaultNamespace
{
    public class HoldButton : Button
    {
        [SerializeField] private Image fillImage;
        [SerializeField] private float holdTime = 1.0f;

polar acorn
#

Ah, that's what you mean. Button has a custom inspector. You'll need to make your own custom inspector as well to add your fields to it

#

Or just make it a separate script that references a button and use the normal button component

spiral narwhal
#

Why would Unity do my dirty like that. thanks tho

slender nymph
#

i'm honestly surprised button isn't sealed. so many other unity components are

plush zealot
#

is there a way of refrencing a project's assets via code?

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

public class CardLoaderScript : MonoBehaviour
{
    [HideInInspector] public string CardName;
    [HideInInspector] public Image CardImage;
    public void loadCardFromDatabase(int id)
    {   //CardImage = cardImageFromAssets named id
        //CardName = query cardname from database using id;
    }
}```
slender nymph
#

just FYI, that's the UIElements.Image object which is not the Image component you can use on a canvas.
but otherwise, there's addressables or you could create a scriptable object that stores that data

#

there's also technically Resources.Load but the other two options are typically better

brisk nest
#

Im trying to get my player to rotate and walk torwards the direction there facing, im able to walk but not change the directions im facing https://hastebin.com/share/uzajaxamax.csharp

plush zealot
slender nymph
#

the Assets folder does not exist in the form you see in your project window inside of a build, so no. the options I listed are how you can reference an asset via code at runtime

plush zealot
#

ah I see

slender nymph
brisk nest
slender nymph
#

that's not rotating any object. that's just changing the value stored in your value type variable

plush zealot
spiral narwhal
#

You could use the resource folder

slender nymph
#

the resources folder is generally not advisable but i did already list that as a suggestion

plush zealot
#

ah sorry

#

didnt realize

brisk nest
slender nymph
#

it's a value type

plush zealot
#

so I can store images and things in the resource folder when building?

slender nymph
#

that is seriously not recommended.

plush zealot
#

why not?

polar acorn
plush zealot
#

ah I see

brisk nest
polar acorn
#

You copy the value to a variable and modify the variable but you never put it back

#

At some point, gameObject.transform.rotation is gonna need to be on the left side of an =

plush zealot
#

Why do I not see the window option they say should exist?

keen cargo
#

go to package manager in that same window

plush zealot
#

oki thx

plush zealot
brisk nest
#

is there a way that i could get my players rotation to just be the same as my cinemachine camera?

keen cargo
plush zealot
#

ah the link not the title

#

ok ill try

#

ah the link worked tysm

keen cargo
#

👌

mint lion
#

addressables is a built in package - you don't need to download it

keen cargo
#

i myself didnt have it for example

opaque reef
#

how can i get the bounding box of a collider when its not axis aligned?

plush zealot
#

does anyone here have experience with addressables?

mint lion
plush zealot
rich adder
plush zealot
#

didnt see, thanks

opaque reef
# opaque reef how can i get the bounding box of a collider when its not axis aligned?
            foreach (var houseObject in houses)
            {
                var collider = houseObject.transform.gameObject.GetComponentsInChildren<Collider>().FirstOrDefault();
                    TriggerEffectParameters param = new TriggerEffectParameters(id: (ushort)effectIds[UnityEngine.Random.Range(0, effectIds.Length)])
                    {
                        position = collider.bounds.center,
                        scale = collider.bounds.size,
                        relevantDistance = 500f
                    };
                    param.SetRotation(houseObject.transform.rotation * Quaternion.Euler(-90, 0, 0));
                    EffectManager.triggerEffect(param);
            }```
#

only axis aligned gameobjects are returning the correct bounding box

#

but what am i supposed to do? calculate the bounding box in local space and rotate it after?

#

(the top house has the interior perfectly as the bounding box, its just not seen)

brisk nest
#

i finnaly got my player to rotate with the camera but the only problem is how can i get its movements to rotate with it? the player is visually rotating but the movements are still locked https://hastebin.com/share/waxoweciqu.csharp

rich adder
opaque reef
rich adder
#

eg boxcollider

opaque reef
#

and i can't really use box colliders

rich adder
#

why are the shapes not simplified primitives?

plush zealot
#

is it possible to assign a sprite from my assets to a sprite renderer via code. Without assigning it manually in the editor beforehand?

cosmic dagger
#

you have to use mesh colliders?

opaque reef
#

i'm able to get perfectly the bounding box for axis aligned

opaque reef
opaque reef
rich adder
opaque reef
#

No, the buildings are already placed on the map, I need to get the area that the house covers

#

so i just thought of getting the bounding box, which works as shown above, for axis aligned only

#

and since i cant use the Renderer i cant use localBounds and rotate them later

rich adder
opaque reef
#

im not going from localspace to world space

#

the bounding box is already being measured from world space

rich adder
#

right one of those

opaque reef
#

since im using the collider

#

the exact same happens

opaque reef
#
            foreach (var houseObject in houses)
            {
                var collider = houseObject.transform.gameObject.GetComponentsInChildren<Collider>().FirstOrDefault();

                    var localCenter = houseObject.transform.InverseTransformPoint(collider.bounds.center);
                    TriggerEffectParameters param = new TriggerEffectParameters(id: (ushort)effectIds[UnityEngine.Random.Range(0, effectIds.Length)])
                    {
                        position = houseObject.transform.TransformPoint(localCenter),
                        scale = collider.bounds.size,
                        relevantDistance = 500f
                    };
                    param.SetRotation(houseObject.transform.rotation * Quaternion.Euler(-90, 0, 0));
                    EffectManager.triggerEffect(param);
            }```
rich adder
#

its the scale

opaque reef
#

yea but how exactly?

cerulean bear
#
using UnityEngine;

public class oppSpawner : MonoBehaviour
{
    private int numOfOps = 5;
    private int[] ops = new int[5];
    public float startingPos = -10.43f;
    public GameObject spawnable;
    private Vector3 spawnPos = new Vector3();
    private Vector3 spawnRotation = new Vector3(180, 0, 0);
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        for (int i = 0; i <= numOfOps; i++)
        {
            spawnPos = new Vector3(startingPos, 4, 3);
            ops[i] = i;
            GameObject spacesh = Instantiate(spawnable, spawnPos, Quaternion.Euler(spawnRotation));
        }
    }
    // Update is called once per frame
    void Update()
    {

    }
}

why is my stuff spawning in the wrong spot

rich adder
# opaque reef yea but how exactly?

wel when I do usually BoxCollider.size usually it gives me local/transformed so maybe try throwing the TransformPoint on the size, keep the position center as the bounds.center

opaque reef
#

transformpoint transforms it from localspace to world space

#

my scale is already in world space

#

if i do this

#

this happens

rich adder
#

I mean Inverse

opaque reef
rich adder
#

oh shit.. well thats not right

opaque reef
#

wait now its just y and z thats wrong?

#

its like that uniformly for every house

rich adder
#

wonky

opaque reef
#

nvm

rich adder
#

rotation is good but size is whacked?

opaque reef
#

for the box of other buildings its just fucked

rich adder
#

ah yeah that wont do..simplify the outline of the buildings with a box collider? 🤷‍♂️

opaque reef
#

i cant really change the mesh renderer from the buildings

#

the issue isnt even finding the center

#

its just that when the collider isnt axis aligned the bounding box will try to be axis aligned(?)

#

and will just eb the correct size but 90 d or plainly twice the size it should be

#

and i cannot calculate it using localbounds since i cant access the renderer component of the building

rich adder
#

you might have to remap it yourself..

rich adder
tender breach
#

Should I use html for my websites and unity for my games respectively?

cosmic dagger
#

website for what?

tender breach
#

It's going to be art software for the website.

tender breach
cosmic dagger
#

art software? you mean you're making an art program using unity?

tender breach
#

For html it's going to be the art program.

cosmic dagger
#

i don't understand what you're doing? where does unity come into play (how does it relate to unity)?

polar acorn
winged osprey
#

I've been trying to fix the main menu for the past hour. Quite literally, the slots should be saved as slot1.json or slot2.json, or slot3.json, but no matter what i do it saves as slot4, and then it doesnt show up in the main menu (but it should). There is 100% a bug in the code, but i cant find it.
SaveManagerCode: https://pastebin.com/Z66L6U9c

slender nymph
uneven frost
#

Im looking for something very specific and cant find any tutorials on it, does anyone know anywhere I could check to find a tutorial on how to make a flying bird controller as my player in 3D? As in you play as a bird and you fly up by flapping your wings and control direction by where youre looking etc

#

I hope that makes sense!!

cosmic dagger
uneven frost
#

planning on making a game where you play as a dove for my gf since she loves birds but I think i might be in over my head 😭

cosmic dagger
uneven frost
#

oh yeah that makes a lot of sense!!!

#

I didnt even think about it just being a normal player controller wiht just, flapping enabled

#

lol

#

sounds great!!

#

I will prpbably be coming by here a lot tomorrow and stuff when I actually start real work on the project, its currentyly 1:25 AM and I wannma go to sleep in like 30 min or so, so I'll start the coding tomorrow

#

wont get much done in 30 min haha

#

I'll do that :)

winged osprey
#

oh my god now the confirmation dialog doesnt show up i gonna jump into a volcano

forest summit
#

i see

#

does othergameobject refer to the object that is being collided with

steep rose
#

you could use oncollisionenter for simplicity (if using a rigidbody)

winged osprey
#

is it just me or there's not alot of 2,5D games tutorials in unity

forest summit
#

does this mean that the script is inside of the point or the player

winged osprey
#

like you move forward, backward, left, right but you cant jump or go down

forest summit
#

ah ok

winged osprey
#

yeah

#

something like that

#

yeah

#

Well i guess that could help me at some point

#

Wait, do you think it will look better when i make an animation for each direction of my character (WASD and diagonal directions) or just WASD

#

Cause that's rather important

#

The collisions will be rather easy

#

I think

#

i'll check it out rq

#

His character has only 2 movements, left and right, and when he's moving down it remembers the last direction he was walking in

#

Yeah

#

Im overthinking some things right now

rancid tinsel
#

why does this go off despite not clicking anything?

winged osprey
#

It's really hard to tell someone how his game would look like better when you don't know what's the game about haha

rancid tinsel
#

wait nvm im stupid

#

i was looking at the debug which always happens when the method is called...

#

🤠 been wondering why it isnt shooting

#

i didnt even have to run it

#

🤦‍♂️

flat sphinx
winged osprey
#

So like, when game is about slaying enemies on a non moving screen, that is one singular scene for now, the background is literally static, the best would be the 8directional movement i feel like, but then its thinking how to make the hand and the arts and the weapon, you'll have to draw 1 sprite 8 times, and then what about having to draw for example 50 weapons times 8

#

that just feels like too much

flat sphinx
#

yeah i guess it is segmenting your code but having a random function handle input only relevant to itself feels icky

rancid tinsel
#

i think it made sense originally but now ive gotten a bit lost with it

winged osprey
#

making my first game with such amount of things to do wasn't the greatest choice

#

well, i'll try my best i guess

#

i thought it'll be done by 24th december but we'll see

#

yeah not really haha

#

now watch 80 tutorials

#

i kinda realised the time it could take

#

the game idea is nice, everything is nice but now do it is just harsh

#

and it aint even for selling like

#

if i make the game i'll tryhard it myself

#

but like when you struggle with saving a file using c# and you have to write an entire AI for each type of enemy

#

aight imma stop complaining and get to work

#

fine 🖐️

rancid tinsel
#

im getting this error between the last 2 lines - any idea what might be happening? I dont have any Destroy() methods in any script yet

winged osprey
#

tbh it feels like the diagonal sprites aren't really adding much work, but then i look at the animator haha

rancid tinsel
#

WAIT

winged osprey
#

brainstorm

rancid tinsel
#

green needle

winged osprey
#

aight back to depression

cosmic dagger
rancid tinsel
#

but i think i messed up some refernece

cosmic dagger
#

probably missing a reference assignment then . . .

rancid tinsel
#

i was accidentally assigning a prefab in the scene

#

that i forgot to delete

#

don't ask me how 😭

winged osprey
#

@edgy sinew wait one more thing

#

it seems not right for some reason

#

Do you feel it or is it just me

#

cuz

#

it actually seems quite weird rn

#

yeah but the overall structure

#

ah i see it

#

i've noticed few mistakes rn

#

like you cant stop dodging

#

or

#

cant transition from left to down or up

#

oh i had a few broken things with the animations earlier

#

do i need to use the exit block

#

like when i go from dodge left to idle and transition it

#

go for the exit block or the idle state back

#

aight

#

thanks for the help though

rocky canyon
#

technically its against the rules to ping ppl not actively in ur conversation but I don't mind

#

i just got home from installing an axel on my car working in the cold.. soo my brain is spaghetti right now

cosmic dagger
#

i don't know about this "L-shaped rig," but the camera is just offset from the pivot point (center of rotation/movement) . . .

rocky canyon
#

KIA.. and complex enuff to wear me out.. gimme a second to read ur post and ill see what i cant do

cosmic dagger
#

yes, you set where you want the camera to be based on the center (pivot) point. you can move it to either shoulder, up, down, front, back, etc . . .

rocky canyon
#

OTS camera..

  • position is offset
  • slight or zero rotation (make the players centerline closer or at center
    for zooming
  • usually the cam moves closer to the character and/ or aligns directly behind the weapon/character
  • FOV does alot to help.. 30-40 degrees-ish?
#

the cursor/crosshair will be a big part of it too.. (tightening up the crosshair for example when zooming ADS)

#

as for rotation i dont ever remember the camera rotating up and down for any TPS games ive played lately

#

this was the last ThirdPerson mode ive played.. ^ not my favorite b/c when u zoom in u just go str8 to first person

#

soo im probably not the best to ask, heh

#

so i guess ya, ur centerline is to the right of the player

#

and then it acts as normal third-person..

#

the way i did it was a bit magic

#

the actual raycast came from the center of the camera.. (ignoring the player/gun everything)

#

soo it would be accurate.. theres edge cases where u have to solve.. like headglitching a corner for example

#

u wouldnt be able to get a hit.

#

my projectiles came from the gun.. and would just use LookAt() to fly towards the point my raycast says it was aiming

cosmic dagger
#

no, that's not what i meant. i was talking about the original pic you sent. the camera is just at an offset position from the pivot point (the transform or position at where the camera rotates). this can be the center of the player or where ever you want to rotate from . . .

rocky canyon
#

but i never really refined it tbh

#

why u want to add to ur suffering?

#

right hand camera.. left handed weapon?

forest summit
#

when i have a script inside of a game object, does gameObject directly reference the object the script is in?

cosmic dagger
#

don't they talk about that in the video you got the bow n arrow pic from?

rocky canyon
#

Camera-Gun Convergence

#
  • raycast from camera
  • align gun barrel to match raycast hit point
  • fire projectile from gunmuzzle
#

i still anticipate edge-cases to sort out

cosmic dagger
rocky canyon
#
 if (Physics.Raycast(ray, out RaycastHit hit, maxAimDistance, aimLayerMask))
        {
            Vector3 targetPoint = hit.point;
            gunMuzzle.LookAt(targetPoint);
        }```
rocky canyon
#
        {
            // Default to aiming straight```
#

this is def something i'd need to tinker w/ hands-on tho

#

mmhmm make sure to test tho.. for different situations..

#

if i remember correctly when i did something like this.. i had to ignore times when the gun was less than so many units from a wall for example.. else the crosshair and raycast hit point was wildly different

#

i think in that case i just shot from the gun str8 forward.. but idk been a while

cosmic dagger
eternal falconBOT
forest summit
#

cause i tried installing the unity integrator however it doesnt seem to do much for me

cosmic dagger
#

yes, your IDE should have intellisense (along with auto-complete) . . .

eternal falconBOT
rocky canyon
#

yup that was pretty much my solution as well.. if u discover a better one i'd be happy to hear

#

for left handed guns (which i did experiment with) i'd move my camera to also be over the left shoulder..

#

ur original drawing confused me a bit

forest summit
#

using UnityEngine;

public class pointCollection : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{

}

// Update is called once per frame
void Update()
{
    
}
void OnTriggerEnter2D(Collider2D other)
{
    if(other.gameObject.CompareTag("Player"))
    {
        print("collected");
        Destroy(gameObject);
    }
}

}
does this look right for a coin collection script, its not working for me

rocky canyon
#

i found my example..

#

so yea, i was testing looking over the top of the car here

forest summit
#

the coin

cerulean bear
#
using UnityEngine;

public class oppSpawner : MonoBehaviour
{
    private int numOfOps = 5;
    private int[] ops = new int[5];
    public float startingPos = -10.43f;
    public GameObject spawnable;
    private Vector3 spawnPos = new Vector3();
    private Vector3 spawnRotation = new Vector3(180, 0, 0);
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        for (int i = 0; i <= numOfOps; i++)
        {
            spawnPos = new Vector3(startingPos, 4, 3);
            ops[i] = i;
            GameObject spacesh = Instantiate(spawnable, spawnPos, Quaternion.Euler(spawnRotation));
        }
    }
    // Update is called once per frame
    void Update()
    {

    }
}

why is my stuff spawning in the wrong spot

forest summit
#

im just touching the coin nothing seems to happen

#

also how do you delete components off of an object?

cerulean bear
forest summit
#

yes they both do

#

yes

#

oh wait

#

maybe not

#

i just tested it with a rigid body

#

no difference

#

yeah its probably a small issue

#

well see

#

i did not

#

it works

#

thank you

#

will do! thanks for the help

cerulean bear
#

I want them to be evenly spaced out over the screen

plush zealot
#

I'm getting this error message at line 15:
"The Object you want to instantiate is null"

1 using System.Collections;
2 using System.Collections.Generic;
3 using Unity.VisualScripting;
4 using UnityEngine;
5 
6 public class GameAssets : MonoBehaviour
7 {
8
9    private static GameAssets _instance;
10    public static GameAssets instance
11    {
12        get
13        {
14         if (_instance == null)
15                _instance = (Instantiate(Resources.Load("GameAssets")) as GameObject).GetComponent<GameAssets>();
16         return _instance;
17        }
18    }
19
20    public Sprite getSpriteById(int id)
21    {
22        int size = 2;
23        Sprite[] cardArtList = new Sprite[size];
24        #region indexing of cards
25        cardArtList[0] = placeHolderSprite;
26        cardArtList[1] = Umbright_Amalgam;
27        #endregion
28        return cardArtList[id];
29    }
30    public Sprite placeHolderSprite;
31    public Sprite Umbright_Amalgam;
32}```
#

I dont know what is causing this

cosmic dagger
eternal falconBOT
plush zealot
#

ah thx

cosmic dagger
#

if the error states the object you want to instantiate is null, then it's not finding the object/asset you're trying to instantiate. if this is not the full error, post a pic of the actual error message . . .

plush zealot
#

this is the full message

naive pawn
#

Resources.Load("GameAssets") is null probably

#

why not just add that gameobject as a reference though

plush zealot
#

because I'm assigning a sprite to a blank sprite renderer that's on a playing card's prefab.

#

the sprite changes depending on the card but the prefab stays the same

mental palm
#

Is There any way to make the resources folder accessible for players ? Or any other method to access the regular game data folder ? (I want my players to put in their own sprites)

plush zealot
#

from the server

mental palm
#

why would I host a server? 😭 that sounds way more complicated than just accessing the files! Like I want every player to add individual sprites to his game

#

Not to every other players game too

#

Or is server like a file thing ?

naive pawn
plush zealot
#

ah well if youre making a single player game you dont need one

#

I suppose woops

naive pawn
mental palm
naive pawn
#

for future reference, you basically have an XY problem here; start with what you're trying to do, the part you put in parens. that's the important part

mental palm
mental palm
mental palm
#

My fault, misread your message

plush zealot
#

Do I need to import any libraries to access the Resource folder because this is for some reason not working:
Debug.Log(Resources.Load("1").name);

naive pawn
plush zealot
#

OMG

#

im blind

#

ty

plush zealot
plush zealot
#

that was it ty

#

I was trying out earlier if that would change anything

#

but forgot to delete it

queen adder
#

can we tell a PolygonCollider2D to copy the shape of the current spriterenderer? Like doing a Reset (Context Menu) on it?

#

did unity expose the method for that?

queen adder
worthy veldt
#

i want to change music volume in realtime using slider from my options menu, so when the player drag the slider the music volume changed.
how do i change my volume value as the player is dragging a slider ?

#

nvm there is on value changed on the bottom of slider component 🤦‍♂️

willow shoal
#

Hello, Quick question. Where to add in this script for example "speed" so that I can change the speed of this script? ```cs
transform.Translate(Vector3.up * Time.deltaTime);

naive pawn
#

there's no speed there

willow shoal
#

but where i should add

naive pawn
#

you'll have to add your own coefficient

willow shoal
#

ik

#

but where

naive pawn
willow shoal
#

thanks i will try this

little hornet
#

quick question, currently as a beginner, for somehow my character is moving upward while pressing W not moving forward, how can I solve this. Had created and also implyed character inputs

naive pawn
#

wherever in the multiplication you want, since it's associative
multiplying a vector with a float is technically more expensive but it's not really gonna affect anything at this point

willow shoal
#

oh

#

ok

naive pawn
#

or your forwards direction is wrong

#

can't really answer much without any detail

little hornet
naive pawn
#

!code

eternal falconBOT
little hornet
#

idk if this is the right code or not

#

I used the default Character Input Unity had provided, might could be the issue

naive pawn
#

oh you don't need to show this

#

that's generated

little hornet
#

here is a picture of the bindings

naive pawn
#

show what you're actually doing to move

little hornet
#

this one is the the PlayerMotor

naive pawn
#

so you're doing 3d right

#

y is up

#

a Vector2 is x and y

#

you don't need to assign the x and y manually here btw, you can just construct it directly

#

if you were to keep the x/y binding, you could also just Vector3 moveDirection = input; but here you need to remap it

naive pawn
#

so it'd be Vector3 moveDirection = new Vector3(input.x, 0, input.y);

#

also pretty sure you don't need the transform.TransformDirection there

little hornet
#

I'll change it and see the result

#

should I delete the ```cs
moveDirection.x = input.x;
moveDirection.y = input.y;

naive pawn
#

yes, since now you're just creating the vector directly

#

i'd recommend using !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

little hornet
#

K, I'll go check

#

here is the changed code, thanks for the teaching

 public void ProcessMove(Vector2 input) 
 {
     Vector3 moveDirection = new Vector3(input.x,0,input.y);
     controller.Move(moveDirection * speed * Time.deltaTime);
 }
final sluice
#

I have this code
collision.CompareTag works if I leave it as OnTriggerEnter2D, but doesn't if It's OnCollisionEnter2D

#

am I doing something wrong ?

#

It said I need collision.gameObject.Comparetag for it to work

naive pawn
spiral narwhal
#

How do I find out if an object is not destroyed?

foreach (var interactable in _interactables.Where(it => it is not null)) interactable.enabled = false;

I have some interactables that are destroyed at runtime without notifying this script

#

Actually nvm I think it might be != instead of is not because of the unity stuff

north kiln
#

Yes, you can't use modern null checking operators

spiral narwhal
#

Yeah time for Unity to step up its game

#

It's ages behind lol

north kiln
#

their approach is incompatible with the operators, the API would have to be changed entirely

#

as it would break so many things, I'm not sure it will ever happen

#

but we can hope the next gen Unity has some changes

willow shoal
#

how to stop a player when he touch a block? or he is close to boxcolider block/object ```cs
public float speed;

bool MoveRight = false;
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        MoveRight = !MoveRight;
    }
    if (MoveRight)
    {
        transform.Translate(speed * Vector3.up * Time.deltaTime);
    }

    else if (!MoveRight)
    {
        transform.Translate(speed * Vector3.down * Time.deltaTime);
    }
} 
#

i try use box colider but he goes through the wall

ivory bobcat
#

You'll move through the wall if you're teleporting otherwise (that's what changing-position/translation with Transform does)

willow shoal
#

ok thanks

#

i will try this

final sluice
#

Should I abuse FindFirstObjectByType<> as a way to set reference ? What is the best way to refer to something else ?

naive pawn
#

no, just set it directly in the inspector