#💻┃code-beginner

1 messages · Page 293 of 1

solid swift
#
{
    if (isCorrect)
    {
        Debug.Log("Correct Answer");
    }
    else
    {
        Debug.Log("Wrong Answer");
        questionManager.checkCounter();
    }
}
void Update()
{
    if (isCorrect)
    {
        character.transform.Translate(Vector3.right * charSpeed * Time.deltaTime);
    }
}```
wintry quarry
#

Also shouldn't the character be moving with that code? Is this even the same script?

solid swift
#

my mistake, i put the scripts correctly now, the character is moving, but i checked the buttons references and everything looks fine, but same issue persists

#

nevermind, i'll try something else, thanks a lot for help UnityChanThumbsUp

lost anvil
#

What is the best, and most flexible way of incorporating an interaction system? - preferably one that will benefit me down the line when it comes to adding new features and so on.

young warren
west sonnet
#

How can I detect when an enemy is moving on the X axis? I want to use it so I can add a running animation

#

I tried doing rb.velocity.x but that doesn't seem to be working

#

I only get the Debug.Log once, then never again

#

for both, I mean

fossil drum
#

Then you probably have collapse on in your console

ruby python
#

Mornin' all.

I'm playing around with Unity's built in Spline System but having issues with a bit of code.

The idea is that the 'Knots' positions get updated using the KnotTargets objects. The weird issues I'm having is that a/ the random positions that I'm giving the TargetKnots seem to be divided by 100 or something as they're always really small numbers, and b/ (probably me being an idiot) My Lerp isn't working at all (the objects positions just 'teleport' to their new position and it's really confusing (regardless of the value I enter for the speed)

Anyone have any ideas? 😕

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

west sonnet
#

Is this code correct for checking when an object is moving along the X axis? Because it seems to work when the object begins moving, but if the player moves to the other side of the object, it changes to "No Run" and stays there, even tho it's still moving

fossil drum
#

Sure you can do it that way, you probably have the transitions set incorrectly in your animator I think.
But can't say without knowing your whole project, but I would start searching there.

#

I don't even understand why you use x instead of z, are you in 2D?

west sonnet
#

It works if I manually set the bool to true in the animator inspector

fossil drum
west sonnet
#

It works the first time my enemy sees the player. They run, but if the player jumps over the enemy, the enemy transitions to idle and stays there

fossil drum
#

Show a screenshot of your animator then

#

I want to see your transitions

west sonnet
fossil drum
west sonnet
fossil drum
#

Okay, everything seems correct...

#

So if you play the game, with this animator screen open, what does it look like? Do the booleans and transitions work?

west sonnet
#

I guess the boolean works because the Debug.Logs work, but the transitions don't. The first transition from entry to idle is good, then when the enemy sees the player, it transitions to running. But if the player jumps over the enemy, it transitions back to idle and stays there, even if the enemy is moving

manic sundial
#

it might be a very small number, i'd suggest looking if its the case

fossil drum
#

Don't assume, verify.
I think what you made should work, but you can probably just see what's wrong if you play with this screen open.

west sonnet
#

But if I jump over the enemy, the enemy is still running towards me, just in the opposite direction, so surely that's not zero?

fossil drum
#

Huh? I thought you run, then went to idle, and never went to run again?

west sonnet
#

I'll give it a go later, but I've got to go now. Thanks for the help

west sonnet
#

So the enemies x velocity must still be more than 0, right? because it's moving

fossil drum
#

It must be anything other then 0 yeah, not knowing how you move things, having a float being 100% a value is usually not the case. It's almost always somewhere in the region because of float imprecision.

#

So if you want to look if a float is equal to 0.5f, you almost never go through that if statement.

#

What flysand said is correct, just debug.log the velocity. Check if what you think its doing is actually what its doing.

misty obsidian
#

Hi where can I ask about importing models to Unity?

fossil drum
misty obsidian
#

Kk ty

vagrant zealot
#
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
using UnityEngine.UIElements;

public class Attack : MonoBehaviour
{

    private GameObject attackArea = default;

    private bool attacking = false;
    private Animator anim;
    private float timer = 0f;
    private float timeToAttack = 0.25f;

    void Start()
    {
        attackArea = transform.GetChild(0).gameObject;

    }

    private void Awake()
    {
        anim = GetComponent<Animator>();

    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            Attackk();
        }
        if (attacking)
        {
            timer += Time.deltaTime;
            
            if(timer >= timeToAttack)
            {
                timer = 0;
                attacking = false;
                attackArea.SetActive(attacking);
            }
        }
    }
    private void Attackk()
    {
        
        attacking = true;
        anim.SetBool("attacking", attacking);
        attackArea.SetActive(attacking);

    }
}

i have this type of Attack method it works i can deal damage but the problem is with the animation. The animation never ends. Can someone help?

#

when attacking is true the animation starts but it never ends it get stuck at the and

#

couldnt understand what is the problem here

slender nymph
#

what is the condition to transition out of that state

vagrant zealot
#

when attacking becomes false

slender nymph
#

and where do you set that to false?

vagrant zealot
#

the piece i sent i cleared a bit normally in the Attack() function there is attacking = false; at the and

slender nymph
#

that's not the animator's attacking parameter

vagrant zealot
#

how can i set that to false

slender nymph
#

the same way you set it to true

vagrant zealot
#

didnt i set it to true in attacking = true; line

slender nymph
#

no because as i've already pointed out, that is not the animator's attacking parameter

#

you just happen to use that bool to set the animator's parameter right after setting that bool to true

vagrant zealot
#

so im setting the parameter with nim.SetBool("attacking", attacking); line did i understand correctly?

slender nymph
#

yes

vagrant zealot
#

this parameter has to be false so the animation can end

#

so how can i set this parameter false 😄

#

with a proper way i mean

slender nymph
#

look at how you are currently setting that to true. that's how you can set it to false too

vagrant zealot
#
private void Attackk()
{
    
    attacking = true;
    anim.SetBool("attacking", attacking);
    attackArea.SetActive(attacking);
    anim.SetBool("attacking", attacked);

}

did like this and my attacked boolean value is false but not my character does not enter to the attack animation i think the time between the lines are too short

slender nymph
#

what the fuck

vagrant zealot
#

wut

slender nymph
#

i didn't mean literally just copy and paste the line in the same place. obviously attacking is still true there

vagrant zealot
#

can you just write the code so i can understand better

slender nymph
#

no

vagrant zealot
#

downloaded unity like 45 mins ago so i dont have that much knowledge

slender nymph
#

then instead of just bumbling along, you should start by learning wtf you are doing instead of expecting other people to do the work for you. there are beginner c# courses pinned in this channel and the essentials and junior programmer pathways on the unity !learn site will go over what you need to know to use the engine

eternal falconBOT
#

:teacher: Unity Learn ↗

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

vagrant zealot
#

bro i dont need to learn c# im using .net already i dont want you to complete my demo game from start

#

i did the running, jumping and the problem wasnt there for them now this error happens

slender nymph
#

then move on to the next bit where i told you where you can learn to use unity

vagrant zealot
#

and im trying to understand why

fervent abyss
#

hi
hows it called when the script cant be put on the scene and its just in your folder

#

editor script but opposite

#

or whatever

slender nymph
fervent abyss
slender nymph
timber tide
#

scriptable objects?

fervent abyss
fervent abyss
languid spire
#

POCO ?

timber tide
#

plain c# objects

#

lol

slender nymph
ruby python
#

!code

eternal falconBOT
fervent abyss
#

😭

#

sry didnt code for awhile

vagrant zealot
#

@slender nymph solved the problem. problem isnt about the boolean named attacking at all. the line i was trying to run anim.SetBool("attacking", attacking); was in the Attackk() it has to be in Update().

#

when i moved it to there problem solved

slender nymph
#

yes and that's what i was attempting to make you realize the whole fucking time

#

please go learn the basics

ruby python
#

Would anyone be able to point out where I'm going wrong please? I don't know why but Lerp stuff in a loop just won't sink in to my brain. 😦

Everything works great if I move the targetObjects manually, but the lerp only fires once.

 void UpdateTunnelSpline()
    {
        for (int i = 0; i < bezierKnots.Length; i++)
        {
            if (i != 4)
            {
                Vector3 knotTargetRandomPosition = new Vector3(Random.Range(-20f, 20f), Random.Range(-20f, 20f), knotTargets[i].localPosition.z);
                Debug.Log(knotTargetRandomPosition);
                if (knotTargets[i].position != knotTargetRandomPosition)
                {
                    Vector3 knotTargetCurrentPosition = knotTargets[i].localPosition;
                    Vector3 newKnotTargetPosition = Vector3.Lerp(knotTargetCurrentPosition, knotTargetRandomPosition, Time.deltaTime * knotMovementSpeed);

                    knotTargets[i].localPosition = newKnotTargetPosition;
                    bezierKnots[i].Position = knotTargets[i].localPosition;
                    tunnelSpline.Spline.SetKnot(i, bezierKnots[i]);
                }
            }
        }
    }
slender nymph
#

where do you call UpdateTunnelSpline

ruby python
#

In start and in update.

#

Was only in start for testing.

timber tide
#

usually dont use lerp with constant speed

#

even unity says you can in the docs, but you should consider movetowards

slender nymph
#

also yeah, your parameters are more suited to Vector3.MoveTowards which will actually provide constant speed

ruby python
#

Okay cool. MoveTowards I think I know how to do. lol.

timber tide
#

problem with constant speed like this is that it will slow down near the end of the destination

#

so not really linear

ruby python
#

Yeah I get ya.

slender nymph
#

but that is still not related to the issue you described, which was a result of you not calling this method continuously until the target position(s) has been reached

#

alternatively you could just put that innermost bit into a coroutine and loop until the position has been reached in the coroutine with a yield return null each iteration of the loop. then you won't have to rethink too much of your logic since right now each time you call the method a new random position is selected

ruby python
#

Okay, this is my update(), creating a new random position is the intent every time the loop is called.

    private void Update()
    {
        if(Time.time >= timeSinceMoved)
        {
            UpdateTunnelSpline();
            timeSinceMoved = Time.time + 1 / rateOfMovement;
        }
    }
slender nymph
#

yes, please re-read everything i've told you about this issue

#

you clearly did not get it the first time you read it

eternal needle
#

This also doesnt really make sense to be using delta time yet not calling something every frame

ruby python
slender nymph
#

i understood that was the intent, which is why that was part of the reason you should use a coroutine just for the lerping part so you don't have to refactor that

ruby python
#

Yeah, I'm going that route. Sorry, just a misunderstanding on your meaning.

#

(On my part)

slender nymph
#

wdym by "calculate rb.velocity"?

#

so you're actually asking about how to get the object's forward direction to multiply by your speed for the velocity? because that's just transform.forward

ruby python
#

Sorry fellas, but I'm really struggling with this, I know it's going to be something really bloody stupid on my part, but the target objects are still only updating once. 😕

Been looking at it for way too long now and can't seem to see why. 😦

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

slender nymph
#

coroutines do not loop automatically. you actually need to put a loop in there

ruby python
#

Ah bugger it. lol. Thank you.

#

Said it would be something stupid. lol.

slender nymph
#

i do recommend adding some logic to stop already running coroutines if you happen to call UpdateTunnelSpline before the currently running ones have completed

ruby python
#

Yeah, that was the next step. 🙂

hardy lintel
#

does anyone know what could be causing my camera controller script to not work? it shows in the inspector that the x and z values are moving but it doesnt actually move in game

#

my seperate zoom function still works but not the camera itself

#

oh wait never mind

#

my team-mate added a random component to it

#

on the same note though lol. can someone help me change the pivot point on my rotational portion of the code?

#

i want it to pivot around on green but currently its pivot point is in the red area give or take

final yoke
#

hey yall , i have a problem where i set up an obstacle spawner in my 3d runner game . one of the items is a rump that the player can jump on top of but the model is facing the wrong side , i tried rotating it but the spawner keeps spawning it facing the wrong wa

young warren
#

you can just set the rotation in the Instantiate call

#

instead of using Quaternion.Identity

#

find out what the X Y Z rotation you want is, then look up how to convert euler angles(which is what XYZ is) to quaternion

final yoke
#

i want it (the single object in the gameobjects list not the entire list ) to rotate q80 degrees on y

young warren
#

or, just set the rotation of the prefab

final yoke
#

180*

#

i did and it doesnt work

final yoke
#

ok ty

queen adder
#

Can anyone help me a my friend cant figure out why We can get out Project into Add?
like I have the Unity Project but when i click Add its not on my Computer
Im loosing Sleep over this... PLZ help!

young warren
meager crow
#

I am tryna get around with unity and get used to it by following the making of box runner frm brackeys but i have run into a problem.
I am trying to make a score system and i have defined a different variable for the text but whenever i try to put the actual text component in the text variable from the script, it doesnt work?

young warren
#

Text from UnityEngine.UI is the old legacy text

#

you want using TMPro; instead

#

and use TMP_Text instead of Text

meager crow
#

alr lemme try

young warren
#

you're running into this issue because that tutorial is old and still uses the legacy UnityEngine.UI Text

young warren
meager crow
#

ye i get, i also thought that it would be the problem but was not sure as to wat to use. Thanks!

young warren
#

you're welcome

#

you might also sometimes see tutorials use "TextMeshProUGUI" instead of "TMP_Text"

#

but that's because textmeshpro has 2 types of texts; one 3d, and one for 2d UI.
but they both inherit from TMP_Text

#

so just use that. it's easier to type and remember as well

neon ivy
#

I'm making a rhythm game and was wondering, how do I store levels in files so people can make and share them? I thought I could use JSON but can you even save the music in json? UnityChanOops

smoky mauve
#

is there any way to override the max number of steps that a mlagent can do before shutting up during training?

karmic kindle
#

I added the top line to try and fix the issue but Unity is still complaining... What have I missed?

        if (enemy.fromDropship)
        {
            if(Enemy.path == 2)
            {
                target = waypoints.pathPoints2[wavepointIndex];
            }
            else
            {
                target = waypoints.pathPoints1[wavepointIndex];
            }
            transform.LookAt(target);
        }```
keen dew
#

What is "the issue" you tried to fix?

karmic kindle
#

Unless I have mess everything up completely... At first I didn't realise I had to declare "waypoints" in my subroutines but the code isn't setting "target" & I get this

NullReferenceException: Object reference not set to an instance of an object
EnemyMovement.Start () (at Assets/Scripts/EnemyMovement.cs:53)

blissful spindle
#

Hi, I just want to know if using physical camera is better for making a fast paced FPS shooter(if not what are the differences between physical camera and not physical camera)

graceful spruce
#

I made a coin manager script with playerpref for saving on main menu and it works fine. However, I want it to so when the player wins level 1(a scene) then they get 300 coins and it updates on the main menu scene.

This is the coin manager script

{
    public static int coins;
    public Text text;

    // Start is called before the first frame update
    void Start()
    {
        coins = 200;
        PlayerPrefs.SetInt("amount", coins);
        PlayerPrefs.GetInt("amount");
    
    }

    // Update is called once per frame
    void Update()
    {
        text.text = "Coins: " + coins;
    }
}

and here's the win level 1 script

        {
            Destroy(gameObject);
            healthBar.gameObject.SetActive(false);
            Debug.Log("You Won!");
            Time.timeScale = 0;
            winMessage.gameObject.SetActive(true);
            isWon = true;
            CoinManager.coins += 300;
        }```
keen dew
#

presumably you'll have to assign it in the inspector but you'd have to show the whole script

slender nymph
karmic kindle
karmic kindle
keen dew
#

This isn't related to your issue

#

Show the EnemyMovement script

karmic kindle
keen dew
#

Right, you can't do new with MonoBehaviours and it wouldn't even make sense here because you'd just create an empty waypoints component that has nothing in it. You have to add public Waypoints waypoints; and drag the object with the Waypoints component into that slot in the inspector

karmic kindle
keen dew
#

yes

karmic kindle
#

I'm trying to not do that since I don't want to change every object.

karmic kindle
# keen dew yes

The enemy that the script is on, has a path value, I am trying to get that to correlate with the waypoint script and I just can't work out what needs to be done

keen dew
#

You have to have some way to tell the script which waypoints you mean. It can't just magically read your mind

#

Presumably you're taking this code from a tutorial or something, don't they show how it's used?

karmic kindle
keen dew
#

So if you don't want to use a static value you'll have to assign it manually

karmic kindle
#

But even then... the Waypoint is still not showing the correct child values anyway

keen dew
graceful spruce
karmic kindle
keen dew
#

Ok well, good luck with that then

slender nymph
hollow zenith
#

How can I set object rotation to specific value? Like rotation.z = 270?
When I use:

Player.transform.eulerAngles = new Vector3(0, 0, 270);

It doesnt set z rotation to 270, but -90 or 90

graceful spruce
# slender nymph call SetInt when you want to save the value

I tried this but didn't work

        {
            Destroy(gameObject);
            healthBar.gameObject.SetActive(false);
            Debug.Log("You Won!");
            Time.timeScale = 0;
            winMessage.gameObject.SetActive(true);
            isWon = true;
            winCoins = 100;
            int oldCoins = PlayerPrefs.GetInt("amount");
            PlayerPrefs.SetInt("amount", oldCoins + winCoins);


        }```
graceful spruce
slender nymph
graceful spruce
#

winCoins = 100;
int oldCoins = PlayerPrefs.GetInt("amount");
PlayerPrefs.SetInt("amount", oldCoins + winCoins);

karmic kindle
slender nymph
graceful spruce
#

Its not adding the win coins to the main menu coins

slender nymph
#

how have you confirmed that

graceful spruce
#

I have the coin counter ui text it doesn’t update

slender nymph
#

show where you are updating the coin counter's coin value

graceful spruce
slender nymph
#

that does not update the value of coins

#

also !code

eternal falconBOT
slender nymph
#

and at no point are you actually using the value saved in playerprefs and you are still overwriting it

graceful spruce
#

Wait sorry

#

Thats the unedited file

slender nymph
#

at this point it seems you should go over the basics of c# so you understand how code works. there are beginner c# courses pinned in this channel

graceful spruce
#

Im currently not near my laptop give me 2 mins

slender nymph
#

have you just ignored everything i've said since then?

#

i'm not going to continue helping you further. you clearly do not understand the basics of how your code works and should focus on learning to use the language before actually attempting to make a game

graceful spruce
graceful spruce
#

its called a code beginner help chat for a reason

#

I’ll go fix it myself and not have to hear anything from you

slender nymph
#

i never said i was mad. i do not help people who refuse to learn the basics. if you continue to refuse to go learn the basics then i will just block you because i don't need you pinging me for nonsense

graceful spruce
rare basin
#

It is called a code begginer, but if you lack very basic programming knowledge

#

How can we help you

#

If you don't even understand the given help

hollow zenith
#

oh -90

#

I changed it to go from 0 to 315 for all 8 directions.
I had to manually do it tho, need to find a better way 😛

magic pagoda
#

does anyone here have a tutorial on how to make an object bounce off of walls like Fistula from TBOI? Aka DVD logo movement

slender nymph
#

Vector3.Reflect to get the new direction, use the normal of the surface that was bounced off of

magic pagoda
#

welp to the unity scripting API I go.

ionic zephyr
#

How could I do a movement based on Addforce so that the player needs to press the opposite input to stop (Inertia)

#

because Addforce is really difficult to control by itself

modest sluice
#

thes 2 init lines behave differently and as i would expect if the list at branchComponent1.previousEndPoints is working properly, but when i try to log values from the public List<Vector3> previousEndPoints it alwasy is empty or .Count = 0

      Debug.Log("here" + branchComponent1.previousEndPoints.Count);
         branchComponent2.Init(5, 15, branchComponent1.previousEndPoints, rotation, new Vector3());
         branchComponent2.Init(5, 15, new List<Vector3>(), rotation, new Vector3());
slender nymph
#

are you certain there are actually objects in the list? and if those two calls are behaving differently somehow, then you'll need to show the relevant code for that method

modest sluice
slender nymph
#

okay now describe how they are behaving differently

modest sluice
#

if branchComponent1.previousEndPoints has no values both object 2 and 3 here should look the same, but 2 looks as i would expect if branchComponent1.previousEndPoints was returning the correct values (it takes the end points of branch1 and use them as start points rotation sets it off to the side don't mind that)

            var branchObject2 = Instantiate(LSystemBranchPrefab); 
            var branchComponent2 = branchObject2.GetComponent<LSystemBranch>();

            Debug.Log("here" + branchComponent1.previousEndPoints.Count);
            rotation = new Vector3(30,0,0);
            branchComponent2.Init(5, 15, new List<Vector3>(), rotation, new Vector3());

            var branchObject3 = Instantiate(LSystemBranchPrefab);
            var branchComponent3 = branchObject3.GetComponent<LSystemBranch>();
            branchComponent3.Init(5, 15, new List<Vector3>(), rotation, new Vector3());
compact shuttle
#

How can I fix the error?

#

theres something wrong about the 'true' but i dont know what exactly

native storm
#

is the gameOver a gameobject?

slender nymph
eternal falconBOT
compact shuttle
#

GameOver is a Gameobject
gameOver is the function

modest dust
#

You have a ; after void gameOver(), but other than that configure your IDE

native storm
#

yeah you mising the ;

#

Also strange naming convention

compact shuttle
#

Well I use Sublime Text because I am on Ubuntu

native storm
#

You would want to name functions with capitals normally like GameOver

compact shuttle
#

and the configuration isnt working like im sent to the same ssite over and over

slender nymph
compact shuttle
#

ok ill try

modest sluice
slender nymph
#

the namespace they are in is entirely irrelevant

modest sluice
#

i figured but i dont even know where to start

slender nymph
#

keep in mind that List is a reference type. so when you call Clear on previousEndPoints it clears the list that was passed in to the init method as the startatpreviousEndPoints parameter

modest sluice
#

i try and log it with Debug.Log("here" + branchComponent1.previousEndPoints.Count); before i use init

slender nymph
#

so? you pass the same list in before either of those objects use the lists because they don't actually start using them until Start is called, later in the frame or in the next frame.

#

log the info about the lists inside of Start right before you call createBranch() and you'll see what i mean

queen adder
#

Hi can someone help me with the unit 2D game beginner?

slender nymph
#

actually you aren't even passing the same list, you're just creating brand new lists for those subsequent calls so i have no idea what you are going on about with regards to those calls behaving differently

queen adder
#

Why?

slender nymph
#

did you read it?

queen adder
#

so where do i get help? I'm a beginner

#

OH

#

mb

slender nymph
#

i never said this was the wrong place to ask for help

queen adder
#

TDAH

#

sorry

slender nymph
#

although if your actual question is not code related, this is the wrong place to ask and you'd want to use #🔎┃find-a-channel to find the most relevant channel for your question

queen adder
#

K ty

modest sluice
# slender nymph log the info about the lists inside of Start right before you call `createBranch...

both before and after createbranch() it logs count = 15 ```cs
void Start()
{
Debug.Log("here1" + previousEndPoints.Count);

        GameObject BaseGO = new GameObject();
        BaseGO.name = "BaseGO";
        ren = BaseGO.AddComponent<MeshRenderer>();
        BaseGO.AddComponent<MeshCollider>();
        BaseGO.AddComponent<MeshFilter>();
        BaseGO.transform.position = baseLocation;

        mat = new Material[1];
        mat[0] = new Material(Shader.Find("Diffuse"));
        ren.materials = mat;


        //   BaseGO.MeshRenderer.material = new Material(Shader.Find("Diffuse"));
        GameObject prefabObject = GameObject.Find("BaseGO"); //prefabObject
        plantPrefab = prefabObject.transform;  //prefabObject

        createBranch();
        Debug.Log("here2" + previousEndPoints.Count);
    } ```
slender nymph
#

and is that what you expect it to be?

modest sluice
#

yes

slender nymph
#

also for the love of god stop with the useless "here" bs in your logs. log some actually useful info

queen adder
#

So, i was following the tutorial (2d Beginner: Adventure game) but when i was at Add code to make the player character move the course made me write this script:

#

But when i execute it the duck don't move

slender nymph
#

because you forgot to write the next line

queen adder
#

script: using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    Vector2 position = transform.position;
    position.x = position.x + 0.1f;

}

}

#

Wdym?

slender nymph
#

i mean you are missing the next line of the code

queen adder
#

oh...

#

Sorry i have TDAH

slender nymph
#

i have no idea what that means

queen adder
#

adhd

slender nymph
#

yeah don't make excuses. i know for a fact adhd does not prevent someone from following a tutorial

queen adder
#

well now it's working... But wait

polar acorn
#

So does nearly everyone in this server.

Code still needs to exist to do something

queen adder
#

why the ducks are clonning?

slender nymph
#

you've changed the clear flags on your camera to don't clear

polar acorn
queen adder
#

What

queen adder
#

to default i mean

#

Sorry it's my first day

slender nymph
#

right click the camera component and just reset it

queen adder
#

ok

slender nymph
#

also consider going through some proper courses instead of following a random youtube tutorial that isn't even providing good code/info

queen adder
#

i'm not

#
Unity Learn

In this tutorial you’ll create a GameObject for the player character and move it using your own customs script. By the end of this tutorial, you’ll be able to do the following: Create a GameObject using a sprite. Describe how 2D positions are controlled in Unity. Write a custom C# script to set a GameObject’s position using information stored in...

#

It's literally a unit course

#

unity* i mean

#

but the layer is already default @polar acorn

slender nymph
#

nobody said anything about the layer

queen adder
#

OH

polar acorn
queen adder
#

It's cuz i can't right click on it

polar acorn
slender nymph
native storm
#

Funny how the tutorial isn't even explaining the use of Time.deltatime

slender nymph
#

especially since 99% of beginners following a tutorial tend to find bogus ones

queen adder
#

Well, I managed to reset the camera but it keeps cloning

slender nymph
#

it's not cloning. your clear flags are still incorrect

queen adder
#

i need to reset here? Right?

slender nymph
#

it'll be in the environment settings i think

polar acorn
native storm
#

Does it have that option?

polar acorn
#

You need to set something to clear up the previous rendered image. Right now it's not doing that so it's just layering every frame on top of the last

#

A.k.a. windows solitaire effect

slender nymph
#

in the URP camera it's called Background Type

#

should be set to Solid Color not Uninitialized

solid swift
queen adder
slender nymph
solid swift
#

ahh!! thank you

polar acorn
# queen adder where

It's called background type in URP. Yours is set to skybox but you have no skybox material. Change that to solid color for now.

queen adder
#

OH so that's the problem?

#

OH

native storm
#

gotta keep im mind if it does not accept something it usually is because the type it accepts does not correspond to what you are giving it

queen adder
#

ok i'm dumb

#

i just skipped that part cuz i thought it was just to change background color

#

but i like the black color...

solid swift
#

i want an image to be in place of that white box in the middle of screen, so i was trying to drag that into the inspetor so that its replaced with the script, but now that i found its sprite renderer thats there i cant get it to be replaced by a sprite, how should i do that?

queen adder
#

So i didn't changed that

solid swift
slender nymph
polar acorn
polar acorn
modest sluice
#

the log here Debug.Log("previousEndPoints called from LSystem before creating branch2 = " + gets run before the LSystemBrnach method for branch1 runs so it returns 0. how can i make it wait for the branch to be finished before logging it ?

        void Start()
        {
           
            // Instantiate LSystemBranch object
            var branchObject1 = Instantiate(LSystemBranchPrefab); // Assuming you have a prefab for LSystemBranch
            var branchComponent1 = branchObject1.GetComponent<LSystemBranch>();

            Vector3 rotation = new Vector3(0, 0, 0);
            branchComponent1.Init(8, 15, new List<Vector3>(), rotation, new Vector3()); 
            var branchObject2 = Instantiate(LSystemBranchPrefab); 
            var branchComponent2 = branchObject2.GetComponent<LSystemBranch>();

            Debug.Log("previousEndPoints called from LSystem before creating branch2 = " + branchComponent1.previousEndPoints.Count);  // this line has no values for branchComponent1.previousEndPoints
            rotation = new Vector3(30,0,0);
            branchComponent2.Init(5, 15, branchComponent1.previousEndPoints, rotation, new Vector3()); // this line has values for branchComponent1.previousEndPoints
slender nymph
#

if you want the code that is on those object's Start methods to run when you call Init, then just put that code into Init instead

modest sluice
#

thanks, i did not realize they were async, would yield return how would i have to change it to use yield return?

slender nymph
#

they are not async

#

nobody said anything at all about any of this being async. Start is just called at a later time for these objects. only Awake and OnEnable are called immediately upon instantiation. then Start is called later in the frame or the next frame depending on when in the frame the object was instantiated. and your methods, being not asynchronous, will not be interrupted by that Start call. so this entire method here will have completed running before start is even called for any of those instantiated objects

modest sluice
#

thank that clears up a lot

slender nymph
#

again, if you want the code that is in Start to have executed by the time you instantiate the next one, put that code into the Init method instead

vapid mesa
#

how i can write my code in the chat ??

hexed terrace
#

!code

eternal falconBOT
dry tendon
#

Does anyone knows why this is not working? ```csharp
public void OpenPdfFile()
{
// Obtener la ruta completa del archivo PDF
string pdfPath = Project.RootFolderPath + "/Manual/" + "DataCraft_Manual.pdf";

        // Verificar si el archivo existe
        if (System.IO.File.Exists(pdfPath))
        {
            // Abrir el archivo PDF con la aplicación predeterminada del sistema
            Process.Start(pdfPath);
        }
        else
        {
            UnityEngine.Debug.LogError("El archivo PDF no se encontró en la ruta: " + pdfPath);
        }
    }``` It is supposed to open a pdf located on assets... but when i click the button it doesn't do nothing...
hexed terrace
#

first, use interpolated strings -> string pdfPath = $"{Project.RootFolderPath}/Manual/DataCraft_Manual.pdf";
(no idea why you were concatinating manual and the pdf anyway..)

Secondly, log out the path, make sure it is correct
Debug.Log($"Path is: {pdfPath}");

smoky mauve
#

is there any way to calculate roots with a different index than 2?

cobalt urchin
#

heeeelloooo i just starded unity and i want a sword in my game i have made a sword in blender and made some attacks/animations soyou now can attack with mouse button 0 and 2, but how do i make my sword deal damage

rapid mountain
modest dust
rapid mountain
cobalt urchin
#

thanks

dry tendon
#
        public void OpenPdfFile()
        {
            UnityEngine.Debug.Log("Openning file");
            
            string pdfPath = $"{Project.RootFolderPath}/Manual/DataCraft_Manual.pdf";
            UnityEngine.Debug.Log($"Path is: {pdfPath}");
            
            if (System.IO.File.Exists(pdfPath))
            {
                Process.Start(pdfPath);
            }
            else
            {
                UnityEngine.Debug.LogError("El archivo PDF no se encontró en la ruta: " + pdfPath);
            }
        }```
slender nymph
dry tendon
slender nymph
#

use your file explorer to navigate to that path

#

hint: you cannot because it does not exist

dry tendon
#

no?

slender nymph
#

if you want to get the path to the project's Asset folder (and if this is for editor only), then just use Application.dataPath

dry tendon
hexed terrace
#

🤦‍♂️

slender nymph
#

no, remove the RootFolderPath bit from that because it is literally just Assets

#

and use Path.Combine when combining strings for a path

dry tendon
slender nymph
dry tendon
slender nymph
#

now tryitandsee

dry tendon
#

Assets\Plugins\DataCraft\Scripts\Editor\Window\Pages\Page 3\SettingsPage.cs(58,30): error CS0103: The name 'Path' does not exist in the current context

slender nymph
#

make sure that your !IDE is configured so that you can use the quick actions to add the correct using directive

eternal falconBOT
solid swift
#

hello again, if moving between scenes and the new scene has different music from the previous, how do i make it so that the previous scene's music is stopped? I have the main menu music with a DontDestroyOnLoad script, but now i made a new script for the music in the specific scene but it doesn't work

slender nymph
#

that if statement will never be true

solid swift
#

ahhh nevermind i see now 🤦‍♀️

#

is there a way to write it so that it checks if its anything other than the instance?

slender nymph
#

why not look up how to implement the singleton pattern in unity? that's what this is, a very naive implementation of that. so look up the correct way to do it

#

but also, is there a specific reason for this to be a singleton?

solid swift
#

ok thank you!! i dont know what a singleton is so i'll read about it

slender nymph
#

translate the error please

dry tendon
slender nymph
#

and is there a PDF file at that path?

dry tendon
slender nymph
#

that is not the same path that you are checking

dry tendon
#

True! let me check it

gray crest
#

is there anyway to stop moving objects from looking blurry if my game needs to be set to 30fps

dry tendon
fast glade
#

Hey guys! 🙂
I want to create an FPS Shooter and i wanted to ask how can i check where i am aiming at? I got something with Raycast, but as soon is a start to look away from obstacles, my bullets keep flying to the last Raycast. How can i do it more "free"?

native storm
#

Do you cast them from the center of your screen (Camera)?

karmic kindle
#

I've finally got my code to run and enemies follow two paths... but they get to the second waypoint and then move to the end of "path1"... this is the code to generate both paths -

        for (int i = 0; i < PathPoints1.transform.childCount; i++)
        {
            pathPoints1[i] = PathPoints1.transform.GetChild(i);
        }
        
        pathPoints2 = new Transform[PathPoints2.transform.childCount];
        for (int j = 0; j < PathPoints2.transform.childCount; j++)
        {
            pathPoints2[j] = PathPoints2.transform.GetChild(j);
        }```
native storm
#

Is PathPoints1 a gameObject you serialized?

compact shuttle
#

Its still the same

#

i configured the ide now

#

and changed names

#

but its still not working

hexed terrace
karmic kindle
compact shuttle
#

here another picture

#

(with code)

#

how can I fix the Set Scene true?

hexed terrace
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

native storm
hexed terrace
#

Follow the guide correctly.

compact shuttle
#

I did

hexed terrace
#

n't

compact shuttle
#

I cant choose VSCode

karmic kindle
native storm
#

then i have no idea, you would have to show more code if you want more accurate help from people

compact shuttle
#

ok wait

karmic kindle
# native storm then i have no idea, you would have to show more code if you want more accurate ...

Here's the full waypoint script - https://pastebin.com/FAAsDBdB - here's the code that's checking it

    {
        if (wavepointIndex >= Waypoints.pathPoints1.Length - 1 || wavepointIndex >= Waypoints.pathPoints2.Length - 1)
        {
            EndPath();
            return;
        }

        ++wavepointIndex;
        if(Enemy.path == 2)
        {
            Debug.Log("I'm path 2");
            target = Waypoints.pathPoints2[wavepointIndex];
        }
        else
        {
            Debug.Log("I'm not path 2");
            target = Waypoints.pathPoints1[wavepointIndex];
        }
        runBack = false;
    }```
hexed terrace
# compact shuttle

yeah, you really need to make the effort to get VSC working correctly, there are errors here that aren't underlined

short hazel
#

If you just installed VSC, restart your computer (or log out then back in) so changes it made to the system's PATH are applied.

torn kettle
#

Trying to make it where the player cannot tap the cube to fly into outerspace. Anyone see an issue with my script? Everything it tagged correctly.

hexed terrace
#

What sets can jump false? -> share your !code

eternal falconBOT
hexed terrace
#

C# is case sensitive, look at your OnCollisionExit method

torn kettle
#

Thank you for pointing that out, I've fixed it but my issue is still prolonging.

hexed terrace
#

Send a screenshot of your IDE

hot palm
#

How do static parameters behave in unity?

torn kettle
hexed terrace
torn kettle
#

I tried looking it up before asking, still couldn't figure it out. Is this what you're looking for?

ruby python
#

Hi all, would someone be able to check over this and see where I'm stuffing it up please? In my head this should work, but I'm thinking I've got an order of operation wrong somwhere 😕

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

Video for reference.

https://streamable.com/uybaza

The idea is that when each of the segments reaches a certain rotation, its rotation 'resets', so that it gives the illusion of an endless tunnel.

Watch "2024-04-07 16-58-32" on Streamable.

▶ Play video
eternal falconBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

torn kettle
#

Looking into it now, thanks man.

hexed terrace
#

You also have unsaved changes... did you save it after changing the OnCollisionExit ?

karmic kindle
hexed terrace
#

1- dont cross post
2- it's not an advanced topic, delete from there

karmic kindle
hexed terrace
#

You wait a bit and bump the question

#

I'm looking at your code now, what's the problem?

karmic kindle
#

The enemies walking along path 2 will jump to one of the waypoints on path 1, then go back to path 2... and vice versa with enemies on path 1. I've deleted the child objects and recreated them in unity but it still acts the same

karmic kindle
hexed terrace
#

share the full movement class

karmic kindle
hexed terrace
#

If I were you, I wouldn't keep querying Waypoints for the next target.
In Start() I'd ask Waypoints for the path, and cache the path in EnemyMovement

Psuedo-y code

//enemy movement
private Transform[] path;

private void Start()
{
  path = Waypoints.GetPath(Enemy.path);
}

// waypoints
public Transform[] GetPath(int index)
{
  if (index == 1) { return path1; }
  
  return path2;
}```
#

then your movement is simplified to just using the path cached in EnemyMovements

karmic kindle
#

😭

languid spire
#

Also why are you caching Enemy.path and then not using the cached value?

karmic kindle
#

Is that just because there's no answer for why it isn't working? 😅 I've spent so long on getting this far... for it to act so weird... like... my brain

hexed terrace
#

It's because your code is VERY messy, lots of repeated code all over and I cba to debug it to find the problem... when this would clean it up dramatically and hopefully stop the problem happening -> as EnemyMovement will only have access to 1 path.

languid spire
native storm
languid spire
#

Yes, I get the impression the OP has never heard of passing parameters into a method

hexed terrace
#

They're a beginner/ student.. so, probably not yet

karmic kindle
#

I'm an amateur, I get help from people who fix broken code but there's never a teacher to say "do this" but even then, like Carwash has suggested, I'm not confident enough to change all of the code to reflect that change.

hexed terrace
#

and you never will be, if you never attempt it

#

I am here for a bit to help, create a thread

honest vault
#

happened to me before and I fixed it I'll look up the code

karmic kindle
slender nymph
karmic kindle
slender nymph
#

and no, random youtube tutorials that teach you unity concepts without teaching you the requisite c# and basic programming concepts are not sufficient

karmic kindle
rich egret
#

When I tried to enter the project from another computer, the text looked like this, does anyone know how to fix it?

slender nymph
languid spire
# karmic kindle Hah, wanker. Not all of us start with a teacher in a school or from the very ba...

That was not snark, just an observation. an example for you

    void Start ()
    {
        PathLength(Pathpoints1);
        PathLength(Pathpoints2);
    }
 
    public void PathLength(Transform[] Pathpoints)
    {
        for (int i = 0; i < PathPoints.transform.childCount; i++)
        {
            if (i == PathPoints.transform.childCount - 1)
            {
                return;
            }
            else
            {
                    int j = i + 1;
                    float calculatePath1 = Vector3.Distance(pathPoints[i].position, pathPoints[j].position);
                    totalLength1 = calculatePath1 + totalLength1;
            }
            Debug.Log("This is the path length #1 " + totalLength1);
        }
    }
karmic kindle
#

Thank you for all making an example of me. I hope the other beginners are also reading this.

karmic kindle
languid spire
#

Anyway looking at your code to only thing I can see possible wrong is that Enemy.path is changing or the Transform children in the path are not set up correctly

karmic kindle
hexed terrace
#

make a non-static public field so you can see the path transforms in the inspector

vale karma
#

okay thankuu

karmic kindle
hexed terrace
#

Debug.Log($"Going to {path.name}", path.gameObject);

the path.gameObject makes that log ping the object in the hierarchy

tawny bolt
#

its a code anout when time slows down and aftera few sec it resumes and u can cancle it by leaving the shift open

hexed terrace
#

Read the docs for GetKeyDown

tawny bolt
#

ok iwill

#

i dont get what youre trying to tell me

hexed terrace
#

First line of the description..

fervent abyss
#

sup mates
i have an enum tabs that user is currently in, and they have numbers assigned. Im trying to do OnTriggerEnter and for example select other enum value by 1, but it doesnt work

public CurrentTab currentTab;

    public enum CurrentTab{
        AccountInfo = 0,
        Online = 1,
        Controls = 2,
        AppInfo = 3,
        Shop = 4
    }

if(arrowKey == ArrowKey.DownArrowKey && (int)computerUI.currentTab != computerUI.tabs.Length){
                computerUI.currentTab++;
                computerUI.tabs[(int)computerUI.currentTab - 1].SetActive(false);
                computerUI.tabs[(int)computerUI.currentTab].SetActive(true);
            }
slender nymph
#

be more specific about what isn't working

languid spire
#

missing (int)
computerUI.currentTab++;

slender nymph
#

that's not necessary

fervent abyss
#

yeah otherwise it would give an error

#

ok basically

raw kindle
#

I have two objects with a composite collider2d, when I move one to the other it just goes through it, but if I move it to an object with a box collider2D it collides like normal

fervent abyss
#

I have this enum value (number 0) on default

#

and i want OnTriggerEnter to +1 the enum and switch it to the next enum value

#

but it doesnt work

slender nymph
#

again, be more specific about what exactly is not working

#

and what debugging you have done to confirm that things are not working the way you expect them to be

fervent abyss
slender nymph
#

and have you bothered doing literally anything at all to ensure that code is running?

slender nymph
#

care to share with the class? or am i meant to read your mind

raw kindle
fervent abyss
# slender nymph care to share with the class? or am i meant to read your mind
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

public class ArrowKeysScroll : MonoBehaviour
{
    [SerializeField] ComputerUI computerUI;
    [SerializeField] ArrowKey arrowKey;
    enum ArrowKey{
        UpArrowKey,
        DownArrowKey
    }    

    void OnTriggerEnter(Collider other){
        if(arrowKey == ArrowKey.UpArrowKey && computerUI.currentTab != 0){
            Debug.Log("pressed up");
            computerUI.currentTab--;
            Debug.Log("pressed up 1");
            computerUI.tabs[(int)computerUI.currentTab + 1].SetActive(false);
            computerUI.tabs[(int)computerUI.currentTab].SetActive(true);
        }

        if(arrowKey == ArrowKey.DownArrowKey && (int)computerUI.currentTab != computerUI.tabs.Length){
            Debug.Log("pressed up");
            computerUI.currentTab++;
            Debug.Log("pressed up2");
            computerUI.tabs[(int)computerUI.currentTab - 1].SetActive(false);
            computerUI.tabs[(int)computerUI.currentTab].SetActive(true);
        } 
    }
}
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ComputerUI : MonoBehaviour
{
    public GameObject[] tabs;
    [SerializeField] int startTabNumber = 0;
    public CurrentTab currentTab;
    public enum CurrentTab{
        AccountInfo = 0,
        Online = 1,
        Controls = 2,
        AppInfo = 3,
        Shop = 4
    }

    void Update(){
        Debug.Log((int)currentTab);
    }
}
slender nymph
#

for example, you can print the value of the enum variable before and after you increment it

tall stag
#

theres gotta be a better way to do this right?

slender nymph
#

do you know what a method parameter is?

tall stag
#

i think so

#

the thing in the brackets right

slender nymph
#

yeah so use one

tall stag
#

do i check like for the name of the button?

slender nymph
#

then all 7 of those methods get condensed into 1

slender nymph
tall stag
#

ohh right i get it now

raw kindle
#

How can I make composite collider of different gameobjects physically collide?

tall stag
#

i forgot that was a thing

slender nymph
raw kindle
slender nymph
#

then it's just a matter of making them not triggers and making sure the rigidbody is set up correctly too

#

and of course moving them in a physics friendly way

raw kindle
#

they arent on trigger, they can collide with box collider2d of different objects

slender nymph
#

well none of this sounds like a code question anyway. so off to #⚛️┃physics with you

raw kindle
#

ok

slender nymph
#

and make sure you provide actual details when posting your issue instead of assuming everyone wants to play 20 questions with you to get the info about your setup

raw kindle
#

sheesh you only asked 2 question chill

hexed terrace
# raw kindle sheesh you only asked 2 question chill

The experienced people that help, don't help just you, he may have had to only ask you 2 questions... but if you're the 10th person they've helped today that didn't provide any/ enough information.. than that's 20+ questions and n minutes wasted

raw kindle
alpine lava
#

hey i have an interesting problem

in my unity editor, ive added the preprocessor directive #if UNITY_EDITOR to run some code that adds a bunch of Sprites to a dictionary in a scriptable object

  • how do i make the data in the scriptable object data persist throughout the editor sessions and in the project build
hexed terrace
#

save the project

ruby python
#

!code

eternal falconBOT
ruby python
#

Hopefully not sticking my head in the lions mouth, but......I have more lerpy issues. lol.

So, I'm rotating an object in a coroutine based on a random rotation float (for the Z Axis). It works, sort of. But I'm struggling a little with some Maths.

IEnumerator UpdateTunnelBankRotation()
{
    float newRandomRotation = Random.Range(tunnelBank.rotation.eulerAngles.z - 45, tunnelBank.rotation.eulerAngles.z + 45);
    Debug.Log(newRandomRotation);
    while (tunnelBank.rotation.eulerAngles.z != newRandomRotation)
    {
        Vector3 newRotation = new Vector3(0f,0f,newRandomRotation);
        Vector3 interimRotation = Vector3.Lerp(tunnelBank.rotation.eulerAngles, newRotation, rotationSpeed * Time.deltaTime);
        //Debug.Log(interimRotation);
        tunnelBank.rotation = Quaternion.Euler(interimRotation);
        yield return null;
    }
}

Because I'm using Lerp, the While condition will never be met, sounds really stupid but been a long ass day lol. So I need to put in a 'threshold' check of sorts (if the rotation is within a certain range of the desired random rotation.

Any pointers please?

languid spire
#

Firstly never check a float for equality

summer stump
ruby python
alpine lava
languid spire
hexed terrace
#

ah, I forget if a dictionary can be serialized.. dont think it can

ruby python
#

Oh I give up, rotations in Unity are so stupid. lol.

alpine lava
# hexed terrace Some solutions <https://www.google.com/search?q=unity+serialize+dictionary&oq=un...

i guess i should just explain the reason im doing this

i want to get all the sprites in my project and add them to a script i made called SpriteLoader. this was so that i dont need to constantly add references to scripts of all the sprites i have in my project since adding them takes a lot of time
the sprites dont exist in the Resources location, so i cant use Resources.Load
for now ive been using AssetDatabase, but that exists only in the editor, and copying the files from the various locations to Resources.Load throws a bunch of annoying GUID errors that i just dont want to see anymore

is there some nice solution for this

hexed terrace
#

copying files shouldn't be producing GUID errors..

sage mirage
#

Hey, guys! I have a question. So, if my native resolution is 2560x1440 and I change it in my game to 1920x1080 for example. Can I somehow reset that resolution back to my native when quitting game? What I done was that in code but it didn't worked. I thought it will work also for the resolution because for my volume values it works.

{
    yield return new WaitForSecondsRealtime(quitButtonDelay);
    int screenWidth = Screen.currentResolution.width;
    int screenHeight = Screen.currentResolution.height;
    PlayerPrefs.SetFloat("MasterVolume", 1.0f);
    PlayerPrefs.SetFloat("SoundsVolume", 1.0f);
    PlayerPrefs.SetFloat("MenuVolume", 1.0f);
    PlayerPrefs.SetFloat("GameVolume", 1.0f);
    PlayerPrefs.SetInt("QualityDropdownValue", 0);
    Screen.SetResolution(screenWidth, screenHeight, FullScreenMode.FullScreenWindow);
    Application.Quit();
    Debug.Log("Game quits and editor play mode stops and our values reset to default!");
}```
alpine lava
hexed terrace
#

you can copy/ paste/ duplicate files without issue.. I do it all the time, zero GUID errors..

Don't copy the meta files.

alpine lava
#

how should i be converting the PNG file to a sprite then if i dont take the meta file with it

hexed terrace
#

or cut+paste

#

it'll create a new meta file ..

alpine lava
alpine lava
#

which is why i copy the meta file

hexed terrace
#

and then you select all and set them as sprites in bulk

alpine lava
#

is there a way to do this in code ?

#

i dont want to do this manually

hexed terrace
#

probably, but click first image -> click last image with shift -> change settings is a lot quicker

alpine lava
#

yes i know about mass edits

#

im just asking is there a way to make all png files in a directory into sprites

#

with code *

languid spire
alpine lava
languid spire
#

well you asked the question, that is the answer, so time to read the docs

hexed terrace
#

Google the keyword given to you

alpine lava
#

thanks.

frigid sequoia
#

Any reason left one takes like 4 times more space? I used the same export and import methods and the left one is even smaller in resolution

frigid sequoia
ruby python
#

Okay, what in the love of all that is holy is going on here.

I really don't get it at all, this is driving me absolutely insane. 😕

https://streamable.com/0hx447

It's behaving as if after the first run of the coroutine has finished it's completely ignoring my 'cooldown' timer and the coroutine call in update.

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

Watch "2024-04-07 19-31-10" on Streamable.

▶ Play video
frigid sequoia
#

Try scraping the whole timeSinceMoved thing and just add a reference to the Coroutine and check if it is null (reset the reference of the Coroutine back to null at the end of itself)

torn kettle
honest haven
#

Hi i have a coroutine inside a coroutine like so ``` private IEnumerator WalkTowardsEnemyAndStartSlider(Vector3 targetPos)
{
Animator playerAnimator = player.GetComponent<Animator>();

    StartCoroutine(MoveTowardsPosition(targetPos));
    
    Debug.Log("caling while mocingr");
    
    currentState = GameState.Idle;``` but the debug is being called the same time as the movetowards potion. how can i wait for the movetowards has finished
languid spire
#

yield the startcoroutine

honest haven
#

yield return StartCoroutine(MoveTowardsPosition(targetPos)); like so?

#

its yield return?

#

perfect

#

cheers

ruby python
torn kettle
#

Good afternoon fellas, I'm running into an issue when creating an infinite runner game. I don't want the player to have access to an infinite jump loop. I was going off a youtube video but even with my code matching I'm still having issue.

https://paste.ofcode.org/qqptz43wFF5hHpUUA68nVn (this is mine)

When previously asking for help I was suggested about my capitalization in code and/or my VS Code not being "configured" but it looks fine and I have everything installed. Any suggestions? Anything is appreciated. 🙂

short hazel
hexed terrace
torn kettle
hexed terrace
#

Having the extensions installed doesn’t mean VSC is connected to Unity properly/ fully

torn kettle
#

Thank you guys for your help, I must've been missing something in your suggestions but now I have it properly working. I really do apprecaite it. I owe you a coffe ☕ 😄

tawny bolt
#

hello i slowed down my time everytime i press shift but how do i keep my sens the same when i slowed down time ?

slender nymph
#

what are you referring to when you say your "sens"

#

also !code

eternal falconBOT
tawny bolt
#

what i referr by sens my chracter sensitivity

#

mouse x and y

hexed terrace
tawny bolt
#

i am going to send my player cam code

short hazel
#

That, or not take in consideration deltaTime in the mouse input calculation

hexed terrace
#

by multiplying the movement speed by whatever value

dusk musk
#

Hey everyone! I have a parent and child script. My parent script contains an integer declaration called value. In one of my methods this value is set to 10. Now in my child script, I want to set this value to 5, and other than that run all lines from the parent script. How would I do that?

Parent script: https://gdl.space/yanabaxiri.cs
Child script: https://gdl.space/akomalegul.cpp

tawny bolt
#

can you explain in furthur deatail cuz i a mstill quit new to time understanding

slender nymph
hexed terrace
dusk musk
hexed terrace
#

I don't see why you need 2 scripts for this?

#

Just put the same component on two game objects

slender nymph
#

yeah just serialize the variable and change it for the individual instances

dusk musk
slender nymph
#

you shouldn't be using inheritance just to change the value of one variable

hexed terrace
#

.Find() is terrible to use too btw.. string searches are slow and unreliable, if you spell a game object differently ("Player" instead of "player"), delete it, etc it.. there's no error to say it's not found because the string differs

sage mirage
slender nymph
#

GetComponent wouldn't be helpful at all there because you still need a reference to the object to call GetComponent on

sage mirage
#

So, how to get reference actually XD?

slender nymph
sage mirage
#

I am using GameObject.Find() and GetComponent<>() I don't know how to get reference otherwise

slender nymph
#

click the link i just sent and learn

hexed terrace
#

well you do now, because box just gave you a link..

sage mirage
#

Yeah! Could you please tell me why ?

hexed terrace
#

why what

slender nymph
#

wdym?

sage mirage
#

I am going to learn the new methods later

#

Why not to use Find()?

#

Everytime I am using find it helps me a lot

sage mirage
#

If you know what string you put inside

short hazel
# tawny bolt can you explain in furthur deatail cuz i a mstill quit new to time understanding

Whether your game runs at 100 FPS (deltaTime would be at 0.01), or at 10 FPS (deltaTime would be at 0.1), you would still move your mouse the same distance in the same amount of time, thus making mouse input independent of framerate.
So, if in your player script you have something like xRot += Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime, it's incorrect. The multiplication by deltaTime should be removed as it links mouse input to framerate again, which makes movement unpredictable if your FPS are unstable.

tawny bolt
#

well i removed it and my mouse would not move att all would you like to see my cam script ?

sage mirage
slender nymph
sage mirage
#

But i heard it is not recommended to make every class singleton.

tawny bolt
#

like ?

#

this is how i wrote my cam script

#

removed time.delta time

slender nymph
#

then reduce the values of sensX and sensY

#

and show the rest of the code if it isn't working for some reason now

short hazel
#

Decrease the sensitivity by a factor of 100, deltaTime is small so it was bringing the values way down

hexed terrace
sage mirage
#

You actually making instances of the class nothing else if I am not wrong

hexed terrace
#

Right, but you shouldn't be asking.. you've been given a link which explains it all

sage mirage
#

I hate reading to tell you the truth a lot of things something very short ok but I really don't like that method. I prefer to see tutorial or to hear it from someone.

#

It's not my learning style

#

I don't say that I don't like to read books if that what you understood

queen adder
sage mirage
#

In website there are so many things that I have to catch them all from scratch

#

XD

#

I have to hear something that is straightforward related with my problem

tawny bolt
#

i tried this but then it just broke my cam

slender nymph
#

why are you subtracting 100? that makes 0 sense

#

you reduce the values you have assigned to sensX and sensY by a factor of 100

#

so if it was previously 100 you set it to 1

tawny bolt
#

ok

#

got it

tawny bolt
covert obsidian
#

Hey, I'm trying to run code when a bullet is touching a zombie, I have no idea how and I couldn't find anything useful.
This code is in a script in a zombie, not sure if I have to call the funciton. I am new to unity.

void OnCollisionEnter(Collider other){
   Debug.Log("touched something");
   if (other.gameObject.CompareTag("bullet")){
    Debug.Log("bullet touched");
  }
}
hexed terrace
covert obsidian
slender nymph
#

did you try reading it?

covert obsidian
#

No debug.log is being ran.

ruby python
#

Hey again all,

Sooooo, I finally have my rotation script working the way I want, so now it's just 'quality of life' stuff.

https://streamable.com/hmzejj

Could someone point me in the right direct on how to 'smooth' the rotation transitions? Ideally I'd like them to be smooth and not so jarring.

I did think about maybe lerping the rotation velocity, but not overly sure how to do that for the 'end' of the rotation cycle. 😕

Watch "2024-04-07 20-45-11" on Streamable.

▶ Play video
polar acorn
covert obsidian
#

i originally read it wrong

#

doing what it says

ruby python
fast swan
#

could i have some help with sliding mechanics please

covert obsidian
frosty hound
fast swan
frosty hound
#

That's not a question, try again

fast swan
#

can i have help making a sliding mechanic in my vr game?

summer stump
frosty hound
#

Ok, if you're going to goof around, you're not going to be actually using this server. Read #854851968446365696 on how to ask a question.

frosty hound
#

If your next post isn't a proper one with details on your issue and code to back it up, then you will be muted.

summer stump
fast swan
#

nvm ill ask in the blender discord

summer stump
fast swan
#

no i just want to understand how to make a slide for a vr game

rare basin
#

man, do you understand

#

that you can make sliding mechanic

fast swan
#

no

rare basin
#

in 1000 diferent ways?

summer stump
rare basin
#

with 1000 approaches and designs

#

we don't know what do you mean by slide for a vr game

#

we do not know what have you tried so far

#

and how do you want it to look

#

we are not wizards

fast swan
#

i want a slide

rare basin
#

don't be ignorant and respect our time, ask detailed, specific questions

fast swan
#

for a vr game

rare basin
#

somebody mute this troll

fast swan
#

im so confused

frosty hound
#

Don't flame it then? And we can all move on.

#

@fast swan find a tutorial and then return if you have issues. Otherwise, stop posting, thanks.

fast swan
#

ok

polar acorn
# fast swan i want a slide

You're going to have to explain what you mean by "slide" because that is not something that has a constant definition

polar acorn
fast swan
#

thank you i understand now 🙂

covert obsidian
#

How do you do a setTimeout in C#?

#

Like to do something after x seconds or miliseconds

wraith valley
#

Hello, my cube can fly

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

public class PlayerController : MonoBehaviour
{
    // Start is called before the first frame update
    public float speed = 10f;
    public float velocity = 10f;
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");

        transform.Translate(Vector3.right * horizontal * speed * Time.deltaTime);
        if (Input.GetKeyDown(KeyCode.UpArrow)) { transform.position += Vector3.up * Time.deltaTime * velocity; }
    }
}
#

When my cube flips over, it starts flying up instead of moving forward or backward

shy pollen
#

so my brain is melting over basic maths, Im trying to essentially have a day/night cycle that lasts maybe 100 seconds total, but i would like to have the time of day represented in UI using the usual 24 hour timeframe, how do i go about calculating the seconds, minutes and hours to put on the clock?

keen dew
#

24 hours is 86400 seconds so you make the clock run 864 times faster than real time

shy pollen
keen dew
#

right

hexed terrace
devout spire
#

I'm assuming this is a code problem.

The boxes are colliding, the enemies are correctly tagged, and my code follows what the tutorial I'm watching shows. I figure it's something with the OnCollisionEnter2D function and I'm just being a newbie, but I can't figure it out.

#

Oh yeah and player color is being correctly set, but it shouldn't even matter because something should still be output to the console even if the color doesn't match.

hexed terrace
#

you haven't said what your problem is

devout spire
#

Whoops I copied the question from another server without the title lol. The collisions aren't being detected and nothing is being returned to the console.

hexed terrace
#

side note: use collision.gameObject.CompareTag(string) instead of == string

covert obsidian
#

How do you do setTimeout in C#?

modest sluice
#

why is my array of GO saying out of bounds at 2+?

    public class LSystem : MonoBehaviour
    {
        public GameObject[] branchArray;
        public int numberOfBranches = 500;

        void Start()
        {
            branchArray = new GameObject[numberOfBranches];
            Debug.Log(branchArray[0]);
            Debug.Log(branchArray[1]);
            Debug.Log(branchArray[2]);
            Debug.Log(branchArray[3]); ```
frosty hound
devout spire
# hexed terrace https://unity.huh.how/physics-messages

I figured it out, thank you! It seems I had to enable the Is Trigger element on the enemies' collider components (which is weird that it was off because I downloaded a package for the tutorial )and add a Rigidbody to the player. That website also seems really thorough and helpful.

hexed terrace
#

It's off by default, a package wouldn't change that

#

oh, unless you mean the package had the enemies already setup inside it

devout spire
#

yeah it did

hexed terrace
#

then it's perhaps part of the tutorial to do that setup

devout spire
#

if so i was working ahead a little too much lmao

#

thank u though

frail star
#

Hello , everyone. I'm looking for some idiot help here , but I hate math honestly. I want to calculate a simple percentage. lets say I have 60 questions , 60/60 is 100%. would the calculation be like .. correct answer/total questions * 100?

slender nymph
#

yes

frail star
# slender nymph yes

Ok , so now I would have to reverse this so I could say pass the test with a percent of 70%+ , how many questions would have to be correct to get 70%+

slender nymph
#

(percentage / 100) * total questions

#

and if you keep your percent as just a float from 0 to 1 except for display purposes you don't have to worry about those extra multiplication and divisions

#

it would just be percent = correct / total. and target = percent * total

slender nymph
#

right i never said you wouldn't. just keep the percentage as a float from 0 to 1 and only change it to 0 to 100 for display

open vine
#

Does anyone know why world space buttons don't work? They don't react at all when clicked

slender nymph
#

you have an event listener in the scene and assigned the correct camera as the event camera for the canvas?

open vine
#

Yes I do and thanks

slender nymph
storm pine
#

srry

crisp mountain
#

hello! trying to spawn a thing three times in quick succession. something is wrong with the IEnumerator. it says i have to return some value, but i dont know what to return. here's the code: https://hatebin.com/tyghaiszkr

#

here's the error message, if that helps at all.

slender nymph
#

start by making sure your !IDE is configured. then i recommend reading the docs about Coroutines

eternal falconBOT
summer stump
#

Ah, lag. Boxfriend covered that

crisp mountain
#

got it working! thanks!

lusty flax
#

is it possible to edit the shape of an EdgeCollider2D through code? preferably, by setting the points it goes through in order using an array of positions/waypoints?

kindred nest
lusty flax
#

thank you! this is exactly what i needed

carmine sierra
#

if a gameobject has a canvas component, do all children need to strictly be UI elements?

rich adder
#

also not code question

carmine sierra
rich adder
#

You can put whatever inside

carmine sierra
carmine sierra
frosty hound
carmine sierra
#

ok

frosty hound
#

You can put anything as a child of an object, but only UI components will appear on a canvas.

carmine sierra
#

okay thanks

magic galleon
#

Please could someone let me know how to set a variable in the same script from a coroutine, the coroutine triggers and is supposed to set a new transform.position

https://hatebin.com/zyamphzjsq

modest dust
#

An error pops up?
Doesn't seem to change the position?
Or what?
Provide more details

#

There are several things that could go wrong here depending on what you're doing and how

magic galleon
#

Thanks, it doesn't set it, I can print 'tar' and it is creating a vector 3 for sure but doesn't seem to set the value of targetTransform.position to that vector3

modest dust
#

Print out targetTransform.position and see for yourself if it does set it to tar or not

#

If the position goes back to what it was then something else might be changing the position of that object

#

Also make sure to print the actual values, not just a "tar" string or whatever, if that's what you did

magic galleon
#

Thanks for the advice, the value was constantly null, I changed the variable from a transform to a vector 3 and just used the vector 3 for the target for a nav agent and works now

whole idol
#

Im proud of this 💪 💪 💪 💪 💪

#

btw does anyone know why is he levitating like this over the ground?

#

He is supposed to be touching the ground

#

His feet are literally on the ground touching

untold raptor
#

check ur prefab make sure it is zeroed out

whole idol
#

zeroed out? how?

cosmic dagger
#

its position and rotation values from the inspector . . .

whole idol
#

They're zeroed out

#

seems like he has some kind of meshcollider over him or smth

#

anyway we'll fix that later 👍

cosmic dagger
whole idol
#

yeah but this capsule moves along with the player

#

its on the blue box prefab layer

deft quarry
carmine sierra
#

can someone help me referencing this bool which is inside of a script which is inside of an object in ddol

#
    toplayer2build toplayer2Build;
    [SerializeField] bool player2BuildTurn;
    void Awake() {
        //Dictates whether it's player 2s turn to build or not
        if (toplayer2Build != null) {
            toplayer2Build = GameObject.Find("player2Turn").GetComponent<toplayer2build>();
            player2BuildTurn = toplayer2Build.player2BuildTurn;
        }
    }

this isnt working

#

i just need to get the bool

#

the first time this scene loads, 'toplayer2Build' doesnt exist, the second time it loads, it does exist

covert flower
#

im working in unity and have made a skill tree. what is an easy way to make it so that the skill tree progress saves after leaving the scene

timber tide
#

mr.json

#

well, json works but if you don't care if it persists between game sessions then make sure the data you're writing to and referencing isn't being destroyed between scenes

opal vortex
#

bump, anyone have thoughts on this?

hollow shadow
opal vortex
#

sounds reasonable, i'd love to see an example of how to accomplish that

kindred nest
# opal vortex bump, anyone have thoughts on this?

how often these references can change? If not at all during run-time, you can reference an instance of a MonoBehavior using a [SerializedField] private <Type> <name>;
and then calling a <name>.function() on it. Otherwise I'm not sure what's the question here

timber tide
#

Yeah, take advantage of IDs with scriptable objects as it's easier to manage them with

opal vortex
#

well I don't have any code for that scenario. I've implemented a few events based on tutorials for triggering a response from every possible object with a listener, but when it comes to customizing it further I don't know where to start.

#

would it be as simple as just editing oneventtriggered to have an additional ID argument to reference and check if it matches the object with the listener?

kindred nest
#

you are referencing a single instance of a "die3" component, presumably somewhere in your scene, is that not what's happening when you have that OnEventTriggered() called?

opal vortex
#

but that just kinda leads into how do I get the events to know what object they're supposed to refer to while still being decoupled like events are meant to be

#

no that's just one example, like in this instance there are three dice objects that are all listening for that event, which tells them to apply the number they rolled to a target

#

they have separate scripts that determine the target based on dragging a line to a unit object and sending a raycast to get the targetgameobject

#

so the event has no idea what's being targeted

#

like this, isn't it beautiful

kindred nest
#

is the target different for each of these objects?

opal vortex
#

potentially

kindred nest
#

lovely art btw

#

has that self-made programmer "get shit done" style i love

opal vortex
#

so like currently the dice get an event to tell them to trigger, but the actual trigger relies on having a reference picked up and tracked by the die gameobject to know the target. I want to know how and if it makes sense to switch that part to also be an event

frosty river
#

Quick question: Tutorials I'm looking at have an Object tab under Navigation tab with checkbox "Navigation static" . But mine lacks that tab. How to get the tab or else enable Navigation static?

carmine sierra
#

i know im not meant to cross post but could anyone help in #💻┃unity-talk. i am stuck rn otherwise

kindred nest
frosty river
opal vortex
#

the current event doesn't need to, what I'm trying to work out is a new event that handles passing the specific dice result to the targeted unit

#

or if that's even useful and helpful.

#

in the current state the event that hits all dice triggers the bottom class here to run a function on the object stored from a raycast

#

Can that lower script be switched to use an event instead, and should it?

gray spire
#

So i made a script with a ship that follows the main player, i dont know if im stupid or just dont know but the ship follows the sprite.. sideways and i want it to follow from the front.. how do i fix it

deft quarry
kindred nest
gray spire
#

bad drawing yeah ik'

kindred nest
# opal vortex Can that lower script be switched to use an event instead, and should it?

not neccesarily, no, you should instead try to change the existing UnityEvent to a <GameObject, Target> type ideally, with the Target being whatever script is supposed to be a target. If you don't have that type defined yet and just want to draw it, a simple Transform or Gameobject will do too. You then call that OnEventTriggered with the second argument being the target derived from that Raycast you mentioned earlier

opal vortex
#

thanks, i'll give it a shot

kindred nest
#

I would restrain myself from over-using UnityEvents or loosely-linked Events, especially for core mechanics which this seems to be, and instead rely on [SerializedField] members. I usually use UnityEvents when it comes to non-crucial elements, like launching VFX, SFX, or similar

scarlet skiff
#

I have a an object that falls which has this script, but even when it hits the ground it keeps on rolling/moving, shouldnt this make it stay in place?

jovial sable
#

OfficialUnityDiscord.SetActive(false);

#

I just disabled this whole server

#

BAM

kindred nest
scarlet skiff
#

i think this is about me not understanding how or missing out on something regarding how the gravity and rb works

#

not a code issue

#

i could simply freeze position in the rb component in the x axis but.. i wanna know hwy this didnt work

kindred nest
#

i think this is potentially something to do with a difference between Update and FixedUpdate functions, Update is called each frame, FixedUpdate is called in a fixed interval, which is where physics are calculated for stability. If you want the rigidbody to be rendered completely immobile, you can simply set rb.bodyType=RigidBody2D.Static in the OnTriggerEnter2D. This will make it unresponsive to any outside forces though

#

if you want to keep the current logic, try changing Update to FixedUpdate() and see if that helps

scarlet skiff
#

uhm, even with this, it keeps on rolling

kindred nest
#

usually when something like this happens you want to make sure that code you changed executes in the first place, try adding a simple print("triggerEnter with Ground") somewhere inside that if statement and look in the debug log it if appears

scarlet skiff
#

sigh... u were right

#

how does that even make sense tho

#

the if statement itself did not change

kindred nest
#

I could try and shortly explain this, but the fact that you didn't change the if statement means it's code block did not execute even previously.
You are probably misusing the OnTriggerEnter2D or configured the collider components incorrectly, I'll point you here: https://medium.com/nerd-for-tech/oncollisionenter-vs-ontriggerenter-when-to-use-them-37b08f3249a5

Medium

Depending on various situations you’ll need to make use of Unity events for when physics collisions or triggers occur. An event allows you…

scarlet skiff
#

wait i see the issue

kindred nest
#

common breaking points in collision detection:

  1. collision matrix incorrectly configured(unchecked when you expect them to collide)
  2. OnTriggerEnter used when Collision is what you're looking for and vice versa (see article above)
  3. collision matrix correct, but colliders/gameobjects have incorrect layers set which makes them skip your if statement in this case
scarlet skiff
#

my original problem was that the heart sometimes goes inside the ground, cuz the wya it worked is that it was a trigger collider and i simply just set the speed to 0 when it reaches the ground, but i didnt like how it clips into the ground so the tsrat of my solution was to ustilize a non trigger collider, and i tested a few things out and ended up forgetting to change the ground check to a OnCollision

#

rather than a OnTrigger

#

ye basically point 2 of what u said

woven crater
#

this seem to work on tile class and not tilerule?

carmine sierra
#

how can I get around ddol being exclusively for root gameobjects, I need to save a group of objects

kindred nest
carmine sierra
#

weird but if it works ill do it

teal viper
#

Root objects don't have parents

kindred nest
#

so computer people are historically bad at naming stuff, hence usually the "root" in relation to some tree structure refers to the Object on the top, so parent of all parents in this case

#

or the ones that have no objects above them is a better way to put it

carmine sierra
scarlet skiff
#

is there a way to check if a public variable is being used in a different script without just removing it and seeing if errors pop up?

kindred nest
#

any Object/property has no idea by default what references them, so red squiggly lines from your IDE are your only easy option I'm afraid

#

if you have a structure/system that implement both-ways referencing, it's usually a good time to rethink your strategy anyway, so this shouldn't be a problem too often

teal viper
scarlet skiff
#

thanks

hallow sun
#

??? For some reason, my player's movement speed changes drastically by being selected in the editor.

hallow sun
#

The other objects maintain a regular speed, and falling through gravity is the same...

teal viper
#

Kinda hard to say without seeing the issue.

hallow sun
#

long gif

polar acorn
#

Show your movement !code

eternal falconBOT
polar acorn
#

It's also possible that whatever keys you're using for movement also move the selected object in the inspector

#

so you're moving it twice per keystroke

hallow sun
#
public class FishMovement : MonoBehaviour
{
    [HideInInspector] public Rigidbody rb;

    [Header("Movement stats")]
    public float moveSpeed = 1f;
    public float jumpForce = 1f;
    public float jumpCooldown = 0.5f;

    [Header("Debug stats")]
    public bool underwater = true;
    public bool isGrounded = false;
    public bool isFlopping = false;

    void Awake()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

        // Swim
        if (underwater && Input.GetButton("Jump"))
            input.y = 1f;
        else if (underwater)
            input.y = -1f;
        // Jump
        else if (isGrounded && Input.GetButton("Jump"))
        {
            isGrounded = false;
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        }

        // Basic movement
        rb.MovePosition(transform.position + (input * moveSpeed * Time.deltaTime));
    }

    // When fish hits the floor
    void OnCollisionEnter(Collision col)
    {
        if (!underwater)
        {
            isGrounded = true;
            isFlopping = true;
        }
    }

    // Switch between jumping methods
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Water")
        {
            //Suddenly slow down when hitting the water
            rb.velocity *= 0;
            rb.useGravity = false;
            underwater = true;
            isGrounded = false;
            isFlopping = false;
        } 
    }
    void OnTriggerExit(Collider other)
    {
        if (other.gameObject.tag == "Water")
        {
            //Additional boost when jumping out of the water
            rb.useGravity = true;
            float jumpBoost = jumpForce - rb.velocity.y;
            rb.velocity += new Vector3(0, jumpBoost, 0);
            underwater = false;
        }
    }
}
native seal
#

put any movemenets in FixedUpdate()

#

keep input in Update()

#

also id recommend directly setting the rigidbodies velocity instead of using moveposition

faint sluice
#

If you call a boxcastall in a direction, is the resulting array in hierarchical order or in "first collider found" order?

timber tide
#

not guaranteed so up to you to sort it

#

rather, it probably does add it into a orderly fashion, but if two objects are in the cast radius of a box, there's not discreet distance operations between the two

south sky
#

Yo guys, can a method reference another unity method. Like for example I have the method Movement() and I want to to have that method check for a collision when the player does something in the Movement() script. So is it leagal to do

Movement()
{
  OnEnterCollider2D();
}
cunning rapids
#

Yes

#

Why wouldn't you be able to?

south sky
#

Cool

south sky
cunning rapids
#

Dude

#

You can reference other methods in methods

#

In any programming language, for that matter

south sky
#

Nvm

#

I was wrong

#

Sorry

cunning rapids
south sky
#

Yh I realised bro

#

You dont gotta rub it in😭

cunning rapids
#

Just a useful thing to keep in the back of your mind because it's something you'll be using quite often

south sky
#

Yh true

spring beacon
#

I am creating a simple quiz game after following the basics from this video tutorial (https://www.youtube.com/watch?v=BjgfxH5taUI&t=1229s), and I can't figure out how to retrieve the AnswerIndex value from one script (top right photo) and pass it to the UpdatePointsText function (different script) to check if the AnswerIndex matches the CorrectAnswerIndex. The AnswerIndex value changes based on the button pressed, similar to what was demonstrated in the video.The AsnwerQuestion(int answerIndex) is in a different script from the ones before "
I saved these parts of the scripts, as they are quite lengthy. If more code is needed, please let me know.

In this tutorial series I'm going over how to create a Quiz Game in Unity ready for mobile. If you've enjoyed playing Trivia Crack, and want to create a Quiz Game of your favourite topic, now it's your chance.

This Quiz Game tutorial is implemented using Unity and C#. Some basic c# knowledge is recommended.

⬇Art Assets (Affiliate Link)⬇
https:...

▶ Play video
north kiln
#

!code

eternal falconBOT
north kiln
#

Also there are plenty of ways to access members in other scripts https://unity.huh.how/references - the easiest and most consistent of which is serialized references

covert matrix
#

how to display the tmp text input value from one scene in another?
for example i have a button with a tmp text attached and its input is "placeholder", and i want to show that "placeholder" text in another scene if that button was clicked

keen dew
#

Arrays are fixed size, you can't add new elements. Use a List if you want to do that.

frosty hound
#

Don't crosspost please

carmine sierra
#

gameObject.GetComponent<Camera>().Size -= p1WeaponFire.poschange;

why is this not valid

languid spire
carmine sierra
#

how would I go about zooming out?

#

i can't tell if it's sensorsize (which didn't work for me) or lenshift

frosty hound
#

Depends on what type of camera you're using, perspective or orthographic

languid spire
final yoke
#

for some reason when the collision happens all the functions get triggered but when the y of the object that the script is attached to reaches below -4 it doesnt trigger can anyone help me

slender nymph
#

for starters, you should be using the CompareTag method rather than string equality when checking tags. but also note that it has to collide with something after its Y position is less than -4 for it to do what you want

languid spire
slender nymph
#

if you just want that to happen after it's position has reached that threshold without requiring it to collide with anything, then you need to check the position in Update or FixedUpdate

final yoke
languid spire
final yoke
#

forgot that this line only triggers on collision because i added the transform trigger way after i did the collision trigger , simplr as that

frosty hound
blissful spindle
#

Hi, I am wondering, how do I make a boolean that checks if the player is actually moving? so what I mean is if he is changing his transform position YK private void Move()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");

 Vector3 movePos = x * transform.right + z * transform.forward;

 controller.Move(movePos * speed * Time.deltaTime);

}

#

thats my movement when it comes to just walking

#

and I dont want to lose stamina only if I hold down shift while standing still

#

private void Sprinting()
{
if (stamina >= 1 && Input.GetKey(KeyCode.LeftShift))
{
speed = sprintSpeed;
Debug.Log("player is sprinting");
stamina -= 25f * Time.deltaTime;
staminaSlider.value = stamina / 100;
timeAfterRuning = timeAfterRuningSet;
}
else
{
timeAfterRuning -= 1f * Time.deltaTime;

    if (stamina < 100 && timeAfterRuning <= 0)
    {
        stamina += 35f * Time.deltaTime;
        staminaSlider.value = stamina / 100;
    }
    speed = 5f;
}

}

keen dew
#
isMoving = x != 0 || z != 0;
blissful spindle
#

uuh, I see okay thx 👍

pastel pollen
#

If I have a job A that runs and which results in a capacity for a native container I need to create and pass into job B, is there a way of doing this without creating a sync point by calling A.Complete()? I can't allocate the native container in a job with a dependency from A if I understand it correctly

hexed terrace
#

@lost cypress don't use GetComponent in Update, it's an expensive call and isn't required.. you should be calling it once to cache (save a reference to) the component you need

feral stirrup
#

How do I make it clone from time to time?

timber tide
rare basin
#

did you read it?

feral stirrup
rare basin
#

you want to Instantiate a object every X seconds?

feral stirrup
#

I mean, an object is cloned, but it is not cloned instantly, it is cloned every so often, that is, a new obstacle every 1 or 2 seconds

rare basin
#

so read the link

#

it will help you

#

or use coroutines

#

or custom timer that you will handle in Update

feral stirrup
feral stirrup
#

Let's see if it clones, but only four or five times, and I want it to clone infinitely.

hexed terrace
willow scroll
feral stirrup
# willow scroll Could you, please, explain it a bit more?

When you press the play button, an obstacle appears every 2 or 3 seconds. I have also been told that with the prefab it works, but it is not cloned. I only get cloned 2 or 3 times and it stops cloning, and I want it to clone infinitely

willow scroll
willow scroll
#

You should start the coroutine and instantiate the object, then wait for a certain amount of seconds in an infinite loop

#
private IEnumerator SpawnObjects()
{
    WaitForSeconds intervalWFS = new(2f);

    while (true)
    {
        Instantiate(yourObject, yourParent.transform);

        yield return intervalWFS;
    }
}
feral stirrup
willow scroll
feral stirrup
willow scroll
#

or outside of the class