#💻┃code-beginner

1 messages · Page 576 of 1

swift crag
#

and then it instantiates other prefabs from there

#

This avoids one of the nuisances you may have run into: needing to start the game from the correct scene

still elm
#

I see, are you using singletons a lot?

swift crag
#

A fair bit, yeah. I am looking to get rid of a few of them though

#

e.g. the PlayerManager is going to need to turn into...multiple Players for split-screen

#

Singletons are great for anything that there is always exactly one of at all times

still elm
swift crag
#

Not a ton. One menu scene and a few levels

#

amusingly, the menu does not live in the main menu scene

#

(it lives forever in DontDestroyOnLoad)

still elm
#

I see

#

How did you do that

#

did you do DDOL and then destory?

swift crag
#

so I have this cute little class here

#
using UnityEngine;

namespace Pursuit.Singletons
{
    public abstract class SingletonPrefab<T> : MonoBehaviour where T : SingletonPrefab<T>
    {
        private static T _instance;

        public static bool Safe => _instance != null;

        public static T Instance
        {
            get
            {
                if (_instance == null) _instance = Instantiate(Resources.Load<T>("SingletonPrefab/" + typeof(T).Name));

                return _instance;
            }
        }
    }
}
#
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void OnLoad()
{
    Instance.Initialize();
}
        

this is in my game controller class, which is a singleton prefab

#

it pulls itself up by its bootstraps!

#

one of the first things it does is grab the main menu

#
// make the menu load itself
_ = MainMenu.Instance;

bit of a silly line of code..

#

This is very convenient for me -- it does not matter which scene I start the game in

#

(I do have some editor-only code that lets the GameController recognize what kind of scene in it's in -- it normally doesn't expect to wake up in a gameplay scene)

swift crag
grand snow
swift crag
#

That would be a literal "T"

grand snow
#

is it really? seems a tad dumb if so

swift crag
#

It's a compile-time constant

grand snow
#

but generic classes for the types should get "created" then too and thus substitute T ?

#

or is that not the case in c#

swift crag
#

The identifier is still "T", even after parameterizing the type

#

A metaphor: nameof(x) is not 5, even if x is an int variable that has a value of 5

burnt vapor
swift crag
#

It does sound like it might work that way

#

Maybe if this was c++

burnt vapor
#

typeof is not a constant expression like nameof. nameof is a compile time constant like fen mentioned

#

typeof is runtime

grand snow
#

i honestly just presumed nameof() would work.
wish we had constexpr shiz

swift crag
#

Generic types aren't figured out at compile time

#

(pretend that AOT compilation does not exist here)

#

constexprs would be nice...

#

You can do some very, very basic stuff with const strings

#
private const string foo = "foo"
private const string bar = foo + "bar";
grand snow
#

the amazing const stuff in rust makes me want a bit more for c# and unity

grand sleet
#

Hello 👋 I'll be making a 2D crossword puzzle mobile game and I'm wondering if anyone has any tutorial recommendations or anything that would make an easier start (Youtube videos, Assets to use, Game objects that I'll be needing, etc.). Thank you! 🙇‍♂️

still elm
#

aww naw. I did edit -projectsettings - physics2d - disable collision. I did this because I did not want the player to be obstructed by the food I have placed down. On collison the player's health is being checked to see if it is full or not, if not full it will not destroy the object.

#

I tried physics.Ignorecollision but I couln't make that work. The issue is that Now when I disabled collisions in physics2d in project settings the OnCollisionEnter2d logic is not working anymore. How can I fix that?

slender nymph
eternal falconBOT
#

:teacher: Unity Learn ↗

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

still elm
swift crag
#

sounds like the food should have both a collider (to prevent it from falling through the floor) and a trigger (so the player can detect it)

#

these could be on different layers, too

polar acorn
still elm
#

when I relized wat i did

serene barn
#

is itnormal that trails wont go in the void?

still elm
burnt vapor
still elm
#

but the food does not fall throught the floor because I have no rigidbody on it

polar acorn
serene barn
#

when you shoot a trail it wont go past the border i dont know how to explain

polar acorn
rich ice
#

you mean like anything belove y 0?

still elm
polar acorn
#

Make one of them a trigger and use the OnTrigger methods instead of OnCollision

still elm
swift crag
#

Pay attention to the parameter type that OnTriggerEnter expects

#

as well as whether this is 3D or 2D

#

this walks you through everything

spice dawn
#

anybody know why this player health script isnt working?

eternal falconBOT
polar acorn
#

Also, what specifically isn't working

spice dawn
polar acorn
wintry quarry
spice dawn
polar acorn
spice dawn
spice dawn
#

Should let me modify it right there

spice dawn
polar acorn
swift crag
#

we are talking about compile errors here, which will be listed in the console window

spice dawn
#

Ok

#

I think it's because I didn't write the code correctly

grand snow
#

we can all see that but you need to check the compile error to know yourself why its wrong

#

ideally your IDE would help you out

#

!ide

eternal falconBOT
spice dawn
#

I use VS code so il check that

#

using UnityEngine;

public class Playerhealth : MonoBehaviour
{
public int maxhealth = 10;
public int health;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
health = maxhealth
}

public void Takedamage()

{
if (health < = 0)

{
destroy (gameObject)

}

}

eternal falconBOT
spice dawn
#

this is the code

polar acorn
eternal falconBOT
rich ice
spice dawn
grand snow
#

plz fix your vs code now so it shows the errors in the file

spice dawn
#

Which app do I use in ! Code?

#

There's like 5 links

rich ice
#

only 1 of them works. choose carefully cat_hehe (they all work the same lol)

naive pawn
#

please configure your !ide

eternal falconBOT
grand snow
#

!ide

eternal falconBOT
grand snow
#

ops. click the one for VS CODE

polar acorn
naive pawn
spice dawn
polar acorn
#

This is not an issue with a Youtube tutorial. This is entirely of your own doing

naive pawn
#

go configure your ide

spice dawn
#

I started unity like 3 days ago

toxic yacht
polar acorn
#

then it'll tell them the errors

grand snow
#

🙏 please we urge you to fix your ide it is soo important

spice dawn
#

!ide

eternal falconBOT
toxic yacht
#

Yes fix the ide it'll help you by pointing out the errors. Those errors should also appear in unity itself in the console section.

spice dawn
#

Lemme use this

#

discord please work

#

@toxic yacht what is ide

grand snow
#

code makey program

toxic yacht
polar acorn
naive pawn
trim moon
#

guys is this move script good

grand snow
#

(╯°□°)╯︵ ┻━┻

naive pawn
#

as a beginner they likely aren't going to figure everything out themselves
a language server gives immediate feedback

languid spire
naive pawn
# trim moon guys is this move script good

you can check isGrounded directly instead of comparing it to true
you can use CompareTag instead of comparing the string tag directly
AddForce with ForceMode.Force is already time-dependant, and it should be done in FixedUpdate. you might want to use ForceMode.Impulse there, and also remove deltaTime.
you might want to use GetKeyDown instead of GetKey.

#

isGrounded should probably not be public/serialized

spice dawn
#

"No problems have been detected in the workspace. "

naive pawn
#

if so then you haven't configured it completely
there's very obvious issues in the code you showed

grand snow
#

close the file and open the file again from unity (double click script in project browser) if you have now configured vs code correctly

naive pawn
#

oh yeah also that

spice dawn
#

The problems just aren't appearing I'm not sure if I'm forgetting something or not

grand snow
#

GAH

naive pawn
#

god please do not take pictures of screens

rich ice
#

there aren't enough commands in this server to describe how much my eyes hurt right now

polar acorn
eternal falconBOT
rich ice
#

!screenshots

eternal falconBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

swift crag
naive pawn
spice dawn
#

Hmm, Apparently I do have problems because all compiled errors must be fixed before testing.

rich ice
# trim moon guys is this move script good

you may also want to use a Raycast for the groundCheck. otherwise, if a wall is tagged as ground, grounded will be set to true (even if they're in the air and touching the wall)

toxic yacht
polar acorn
eternal falconBOT
spice dawn
#

Nothing is underlined in red though?

rich ice
naive pawn
#

because either the language server is waiting on a download or something or you havent' configured it properly

polar acorn
swift crag
#

If you didn't follow all of the instructions for VS Code linked above, do that now.

grand snow
#

@spice dawn if you close vs code fully and then in unity do Assets > Open c# project, does this make it work?

spice dawn
#

lemme try

grand snow
#

if you followed the configuration steps it should open the code project and make shit work

spice dawn
naive pawn
#

ah, you didnt open the project folder before...

grand snow
grand snow
naive pawn
#

since vscode isn't an ide in itself it also supports opening singular files outside projects ("open folder")

elfin canyon
#

hi guys i putted 3d model into unity but it wont put itself into working window whats the problem?

naive pawn
elfin canyon
spice dawn
#

You imported it in correct?

trim moon
elfin canyon
naive pawn
naive pawn
spice dawn
grand snow
#

you sure you did all the set up?

naive pawn
#

make sure to give it a bit to think

spice dawn
#

i physically cant find analasyis

#

typo sorry

#

discord pls work

trim moon
spice dawn
#

Where is analysis i cant even find it

grand snow
slender nymph
grand snow
# spice dawn ok done

thats great but the website linked to in the ide info box we kept sending should have explained this too

frigid sapphire
#

Hi, me again. I have this script that gives you a 3x income boost, how could I make it so when I buy an upgrade the increase in multiplier get's 3x'd aswell? Idk how to explain it better basically when I upgrade multiplier gets increased by normal value not the 3x'd value and idk how to do it really
multmult = 3; xt.text = $"3x Active! {Mathf.Round(timero2)}s left"; if(!alreadymulted) { ms.acm *= multmult; ms.mult *= multmult; ms.p4m *= multmult; ms.p5m *= multmult; alreadymulted = true; alreadydivided = false; timero2 = 30f;

ms is MainScript, acm/mult/p4m/p5m are the multipliers from different upgrades, aldreadymulted is just checking if the values have already been multiplied, alreadydivided is set to true once timero2 gets to 0 and the values are divided.
I should be able to do this I just want to get some of your ideas on what would be the most optimized way to do it

spice dawn
#

!ide

eternal falconBOT
naive pawn
#

could you not spam the commands?

slender nymph
eternal falconBOT
polar acorn
spice dawn
polar acorn
#

Just keep the tab open

rich ice
spice dawn
#

ok am I just plain out stupid

#

(Probably)

#

But anyways what the hell I'm on the same page as I was 20 minutes ago

polar acorn
frigid sapphire
polar acorn
grand snow
spice dawn
polar acorn
spice dawn
polar acorn
#

Okay what about all the other steps

rich adder
#

btw you should not configure IDE with compile errors

#

make sure you comment those out first if you have any

grand snow
# spice dawn

press the regenerate button under that bit it may help

rich adder
# spice dawn

looks configured on this part, you need to try closing VSC regen project files button on that page then open script again from unity double clicking, it either will work or spit out .net sdk error

spice dawn
rich adder
#

only the top 2

grand snow
swift crag
rich adder
#

note if you still have compile errors, it will not work no matter wat

swift crag
#

since there is currently a compile error

#

you can just comment out everything in the script to let Unity compile

grand snow
#

delete the file

polar acorn
grand snow
#

can it regen in safe mode?

slender nymph
rich adder
#

if it can't compile its not going to be able to attach well to vsc

#

yea true

#

its cause of packages, it had to connect and if you cant install it wont be able to

signal pollen
#

Hullo, I am trying to figure out how to check either

  1. a boolean/value of a sibling in the heiarchy tree
    or
  2. a boolean/value gameObject (Such as the player)
    is this possible?
    I am trying to prevent my truck from picking up 2 crates, limiting it to picking up only one at a time.
rich adder
signal pollen
#

What do you mean by that?

rich adder
#

dont you have a pickup script?

signal pollen
#

Like refer to itself as currentObject?

#

What is the line needed? I have been searching for it for a while

rich adder
#

with script*

signal pollen
#

I admit it's a really messy code. I have just been hacking away without refactoring yet

rich adder
#

its totaly fine

#

this is beginner channel, we all been there

#

would be easier to read if you sent via links lol

signal pollen
#

Lol

#

Lemme find a pastebin

rich adder
eternal falconBOT
signal pollen
rich adder
#

oh the cube itself has the pickup logic

signal pollen
#

Super messy, and should be redone, with bits and bobs all over the place

#

Should I redo it such that the Truck has the script logic?

grand snow
#

@signal pollen based on what i just saw, the collectable hides and marks it self as collected. You want your truck/player script to track what collectables its holding so you can hold only one.
e.g.

Player player = hit.GetComponent<Player>();
bool pickedUp = player.TryPickUp(this);
if(pickedUp) //do stuff
rich adder
#

I wouldve probably done it the opposite so its easier

#

but basically you can still access player from this

signal pollen
signal pollen
rich adder
# signal pollen Yeah I am figuring that now

so you can store the cube itself and dont even need bools to track, and you can store cube to do other things with it

GameObject theCube

void OnTriggerEnter(Collider col){
if(col.CompareTag("Cube") && theCube == null)
//pickup cube
}```
grand snow
signal pollen
#

oh

polar acorn
signal pollen
#

I see

#

Maybe redoing the scripts as whole is the way to go then\

#

I've done this very messily lol

grand snow
#

for example:

public class Player : MonoBehaviour
{
    private Collectable heldCollectable;

    public bool TryPickUp(Collectable collectable)
    {
        if(heldCollectable == null)
        {
            heldCollectable = collectable;
            return true;
        }
        else return false;
    }
}
rich adder
#

there is probably no reason for each cube to be using OnTrigger methods for each one, rather than player itself has pickup script

signal pollen
#

Yeah that is true

grand snow
#

That is true, the truck/player is the better place to do the picking up logic

signal pollen
#

I used this collectible script cos the Junior Programmer course by Unity did that

rich adder
signal pollen
#

When instead the correct/smarter thing to do is to attach the collectible script from the player persepective

rich adder
#

yeah its common

signal pollen
#

Okay! Time to refactor the whole thing. I have been avoiding it for too long

#

Thank you guys

#

(Although I could just do with sleep)

grand snow
#

no sleep only code

rich adder
#

wait for you to be fully refreshed

#

especially a refactor

signal pollen
#

Aw no meme gifs.

#

Alright night night. Thanks guys

rich adder
#

fun-free zone 😛

grand snow
#

no fun only code

tender stag
#

'SceneManager' does not contain a definition for 'LoadSceneAsync' and no accessible extension method 'LoadSceneAsync' accepting a first argument of type 'SceneManager' could be found (are you missing a using directive or an assembly reference?)

#

im using UnityEngine.SceneManagement

wintry quarry
# tender stag

Most likely you made your own class named SceneManager

#

Try UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(...)

#

or rename your SceneManager class

#

(I bet this code is probably inside your class named SceneManager in fact!)

tender stag
#

its this

#

from fishnet

wintry quarry
#

Yeah the class is named SceneManager

tender stag
#

so am i gonna have to write out UnityEngine.SceneManagement every time?

wintry quarry
#

I mean for one I don't recommend modifying the code inside packages in the first place

swift crag
#

this would also happen if you had a using directive for the namespace that Fishnet's SceneManager is contained in

#

you can use an alias:

using Whatever = Some.Specific.Thing;
wintry quarry
swift crag
#

a common one is

#
using System;
using UnityEngine;
using Random = UnityEngine.Random;
wintry quarry
#

they have in fact ALREADY aliased it for you

#

So you can just use UnitySceneManager

tender stag
#

how?

wintry quarry
#

var scene = UnitySceneManager.LoadSceneAsync(...)

tender stag
#

The name 'UnitySceneManager' does not exist in the current context

wintry quarry
#

Well it would be nice if you shared what the current context is with the class

#

My impression was that you were writing code inside the Fishnet script

tender stag
tender stag
slender nymph
#

note how that code does not have the same using alias

wintry quarry
#

Ok so then you need to add an alias as we mentioned

#

or write out the fully qualified name

#

pick one

#

There are three examples of creating an alias above

swift crag
#

If you had added using UnityEngine.SceneManagement; , you'd have gotten an error when trying to name SceneManager -- it's unclear which type you're trying to refer to

#

UnityEngine.SceneManagement.SceneManager vs. FishNet.Object.SceneManager (presumably)

tender stag
#

im just gonna use this one

#

using UnitySceneManager = UnityEngine.SceneManagement.SceneManager;

tender stag
#

im not sure why the loading bar is behaving this way, it never reaches 100%

rich adder
#

that async is looking wonky

#

looks like it loads the lobby scene again before then going into game

rich adder
slender nymph
#

it only progresses to 90% if allow scene activation is false. but it seems that the issue is that it does most of the loading in a single frame (or at least in less than 100ms) so it fills up to that point, then because it has finished loading by the time the delay has ended it continues without filling the rest of the bar, which leads directly to a 2.5 second wait

wintry quarry
#

you're never going to see a full bar because it will never update the fillAmount when it's == 0.9f which would be a full bar with this code.

mystic lark
#

how come when i spawn a clone game object and i put in update

#

Vector2 dir = Vector2.left;
body.linearVelocity = dir * moveSpeed;

#

but it wont move

slender nymph
#

have you confirmed that code is running? do you have any errors? are there any colliders blocking the object? you gotta provide more details

mystic lark
#

my code is working and correct but maybe its the pipe cuz i put 3 object thoghether?

polar acorn
# mystic lark but it wont move

Several possible reasons:

  1. The code isn't on the object
  2. moveSpeed is zero
  3. The object is moving, but so is everything else so you can't tell
  4. You're actually asleep and hallucinating the computer right now. Please wake up, we all miss you.
  5. You are getting an error preventing this code from executing
  6. Your object is gigantic and it's moving an imperceptibly small amount
polar acorn
#

Basically, more information is required

mystic lark
#

and also the box coliders shuldnt be the problem they arnet tuching

polar acorn
#

What is body?

#

Presumably, a rigidbody of some sort, but which object has it?

#

which object has this script on it?

mystic lark
polar acorn
edgy tangle
# tender stag

You'll obviously have to change some things around (e.g. I am invoking events that you don't have here and you're using async await vs a coroutine), but this is a snippet from my own async scene loading script which works well with progress bars. In my case I have the loading screen UI subscribe to these LoadSceneProgress and LoadSceneComplete events rather than coupling them together.

        var asyncOperation = SceneManager.LoadSceneAsync(sceneName, loadSceneMode);
        if (asyncOperation != null)
        {
            while (!asyncOperation.isDone)
            {
                var progress = Mathf.Clamp01(asyncOperation.progress / 0.9f);
                progress = Mathf.Max(progress, fakeProgress);
                LoadSceneProgress?.Invoke(progress);
                yield return null;
            }

            LoadSceneComplete?.Invoke();
        }
#

ah there's also this fakeProgress thing I have... You can ignore/delete that line unless you want me to explain it :3

mystic lark
slender nymph
#

show the entire PipeMovement script

polar acorn
eternal falconBOT
mystic lark
#

i think im just an idiot

#

let me try something for 1 min

#

yea im an idiot i forgot the

#

body = GetComponent<Rigidbody2D>();

slender nymph
#

pay attention to the errors in your console instead of ignoring them

mystic lark
#

i was staring at my screen for like 10 mins until u asked me to show the full script

tender stag
#

cause im on my phone now

#

and its like multiple lines and shit

#

or paste of code or any website

edgy tangle
# tender stag or paste of code or any website

var asyncOperation = SceneManager.LoadSceneAsync(sceneName, loadSceneMode);
if (asyncOperation != null)
{
while (!asyncOperation.isDone)
{
var progress = Mathf.Clamp01(asyncOperation.progress / 0.9f);
progress = Mathf.Max(progress, fakeProgress);
LoadSceneProgress?.Invoke(progress);
yield return null;
}

        LoadSceneComplete?.Invoke();
    }
#

how about just plain text reply

tender stag
#

that’ll do thanks

tender stag
#

by setting something to false i dont remember what it was

#

and when it finished they set the bool to true

#

it was allowSceneActivation

#

why arent u using that there?

eternal falconBOT
tender stag
#

cause im on mobile

edgy tangle
#

tell that robot who's boss

tender stag
#

lmao

edgy tangle
#

I think sllowSceneActivation might be a new thing in Unity 6...? Or its just something I've never found I needed.

tender stag
#

alright

#

nah im not using unity 6

edgy tangle
#

ah okay

#

yeah I've just never bothered touching it

#

Looking at the documentation though it looks like you will need it to be true for the snippet I added

#

Otherwise you'll get stuck in that while loop

#

because isDone will never be true

#

unless at some point you change allowSceneActivation back to true in the while loop in order to break

#

I guess you could set allowSceneActivation back to true if progress >= 0.9f 🤷

#

But then I don't really see the point in touching it at all

#

Ahh okay in the example in the documentation they show a case where for example you'd want the player to press a button after loading finishes in order to activate the scene. That's what it's for. If you just want it to load when ready then don't bother touching it.

silk pasture
#
    // hi
rich ice
#
  // hello!
forest summit
verbal dome
eternal falconBOT
forest summit
#
using JetBrains.Annotations;
using UnityEngine;

public class PickupObject : MonoBehaviour
{
    public float pickUpForce = 150f;
    public float pickUpRange = 5f;
    public LayerMask isPickable;

    private GameObject heldObj;
    private Rigidbody heldObjRB;
    public Transform holdArea;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            if(heldObj == null)
            {
                RaycastHit hit;
                if(Physics.Raycast(transform.position,transform.forward, out hit, pickUpRange))
                {
                    Pickup(hit.transform.gameObject);
                }
            }
        }
        else
        {
            Drop();
        }
        if(heldObj != null)
        {
            MoveObject();
        }
    }
    void Pickup(GameObject pickObj)
    {
        if(pickObj.GetComponent<Rigidbody>())
        {
            heldObjRB = pickObj.GetComponent<Rigidbody>();
            heldObjRB.useGravity = false;
            heldObjRB.linearDamping = 10;
            heldObjRB.constraints = RigidbodyConstraints.FreezeRotation;

            heldObjRB.transform.parent = holdArea;
            heldObj = pickObj;
        }
    }
    void MoveObject()
    {
        if(Vector3.Distance(heldObj.transform.position, holdArea.position) > 0.1f)
        {
            Vector3 moveDirection = (holdArea.position - heldObj.transform.position);
            heldObjRB.AddForce(moveDirection * pickUpForce);
        }
    }
    void Drop()
    {
        heldObjRB.useGravity = true;
        heldObjRB.linearDamping = 1;
        heldObjRB.constraints = RigidbodyConstraints.None;

        heldObjRB.transform.parent = null;
        heldObj = null;
        
    }
}
verbal dome
#

        else
        {
            Drop();
        }```This looks suspicious
ivory bobcat
forest summit
ivory bobcat
#

You could probably just explain in a sentence or two

verbal dome
#

It would drop the object unless you click the mouse button every frame, at superhuman speed

#

Do you mind linking the tutorial?

forest summit
#

yeah

ivory bobcat
#

I'm assuming gravity is occurring

forest summit
#

yes, what i meant was how when you pick up something in a game like portal or half-life it hovers there in front of you, as if you were making it float

ivory bobcat
#

Should it fall immediately after you pick it up? If not, when should it fall?

verbal dome
forest summit
#

its supposed to fall after you click the mouse button while its already being picked up

forest summit
#

i think i found the issue

ivory bobcat
#

You'd probably want that else inside that if statement: when checking for null

forest summit
#

ok i just did that

#

same thing is occuring however

ivory bobcat
#

Did you save?

forest summit
#

here we go

#

thank you

#

i just noticed something really odd

#

have you ever heard of the game superliminal?

#

the object im picking up is changing size based on my perspective

verbal dome
#

Maybe its parent has a non uniform scale?

#

Meaning x, y, and z are not the same

forest summit
#

i think your right

#

its still doing it, its alright though i think ill be able to find a fix

rich adder
timber tide
#

the scale on that cube is crazy large

forest summit
#

the giant wall or the one im picking up

timber tide
#

I'd unchild the cube and keep the scaling uniform

verbal dome
#

The selected cube isn't the one they are moving

timber tide
#

Actually didnt read the problem but I assume it's being added as a child when moving the cube, but the parent scaling it applying to the cube and it's making it odd-shaped

forest summit
#

the cube is being parented to an empty object that stores the hold position

timber tide
#

Maybe im hallucinating, but looks like the shape of it is changing but could just be perspective

timber tide
#

something's being changed, and ideally keep your scaling uniform

forest summit
#

do you mean keeping my scaling uniform as in not making giant objects

humble quarry
verbal dome
forest summit
#

oh yeah sorry

verbal dome
#

(1, 1, 1) = uniform
(3.5, 3.5, 3.5) = uniform
(1, 2, 3) = not uniform

timber tide
#

also if you parent an object at runtime you need to set the optional bool to keep its world orientation if the parent has scaling other than 1, otherwise it'll act upon the child object

forest summit
#

ok the scaling issue is fixed

timber tide
#

or just not scale the parent at all

timber tide
forest summit
#

its also not moving with my character which is odd

ashen harness
#

Basically the issue im having is I need the camera movement script to rotate the player body but only side to side so it doesn't rotate the body to be parallel with the ground lmao I'm on the verge of a breakthrough to do it but i just can't seem to grasp the process

#

and lemme go grab the code hol up

humble quarry
ashen harness
#
{
    public CharacterController controller;
    public float mouseSensitivity = 100f;

    float xRotation = 0f;
    float YRotation = 0f;

    void Start()
    {
        //Locking the cursor to the middle of the screen and making it invisible
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
        //control rotation around x axis (Look up and down)
        xRotation -= mouseY;

        //we clamp the rotation so we cant Over-rotate (like in real life)
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        //control rotation around y axis (Look up and down)
        YRotation += mouseX;

        //applying both rotations
        transform.localRotation = Quaternion.Euler(xRotation, YRotation, 0f);

    }
}
timber tide
ashen harness
#

i made the reference to the character controller but how do i exactly rotate it like the bottom process``` //control rotation around y axis (Look up and down)
YRotation += mouseX;

    //applying both rotations
    transform.localRotation = Quaternion.Euler(xRotation, YRotation, 0f);```
verbal dome
# forest summit its also not moving with my character which is odd

The whole thing is a bit flawed, you should not use parenting with dynamic rigidbodies.
You can try setting the rigidbody isKinematic To true when you pick it up and to false when you drop it. This won't use any physics though really.
Or you can get rid of parenting and move the picked up rigidbody with a Joint or some forces.

ashen harness
rich ice
#

almost had it lol

ashen harness
rich ice
#
float
int
formatting
ashen harness
#

lmao

rich ice
#

put cs after the ``` to make it format correctly

ashen harness
#

but anyways how could i replicate this bottom half but for the player controller to rotate side to side only

#
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
        //control rotation around x axis (Look up and down)
        xRotation -= mouseY;

        //we clamp the rotation so we cant Over-rotate (like in real life)
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        //control rotation around y axis (Look up and down)
        YRotation += mouseX;

        //applying both rotations
        transform.localRotation = Quaternion.Euler(xRotation, YRotation, 0f);

    }
}```
rich adder
ashen harness
#

it was part of a tutorial i was watching for my old project lmao this is just a reused script for a new project

rich adder
ashen harness
#

it was a survival game tutorial from someone else lmao

rich ice
# ashen harness ``` float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.del...
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
        //control rotation around x axis (Look up and down)
        xRotation -= mouseY;

        //we clamp the rotation so we cant Over-rotate (like in real life)
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        //control rotation around y axis (Look up and down)
        YRotation += mouseX;

        //applying both rotations
        transform.localRotation = Quaternion.Euler(xRotation, YRotation, 0f);

    }
}```
just 2 letters ![guh](https://cdn.discordapp.com/emojis/1084745397618090024.webp?size=128 "guh")
rich adder
ashen harness
#

okay but ignoring the poor choice of delta time , i still don't know how to properly replicate the bottom half for the character controller 🤣

#

could i just replace "mouse" with "controller"? or would that not work

verbal dome
ashen harness
#

yeah its this half

#

        //applying both rotations
        transform.localRotation = Quaternion.Euler(xRotation, YRotation, 0f);

    }
}```
#

yeah?

verbal dome
#

If you only want y rotation, remove the x rotation

rich ice
humble quarry
#

how can i disable a script?

rich ice
#

or this little tick on the left

humble quarry
#

ohhh i see, thanks!

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

public class MouseMovement : MonoBehaviour
{
    public CharacterController controller;
    public float mouseSensitivity = 100f;

    float xRotation = 0f;
    float YRotation = 0f;
    float YBodyRotation = 0f;
    float XBodyRotation = 0f;

    void Start()
    {
        //Locking the cursor to the middle of the screen and making it invisible
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
        float bodyX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float bodyY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
        //control rotation around x axis (Look up and down)
        xRotation -= mouseY;
        XBodyRotation -= bodyY;

        //we clamp the rotation so we cant Over-rotate (like in real life)
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);
        XBodyRotation = Mathf.Clamp(xRotation, 0f, 0f);
        //control rotation around y axis (Look up and down)
        YRotation += mouseX;
        YBodyRotation += bodyX;

        

        //applying both rotations
        transform.localRotation = Quaternion.Euler(xRotation, YRotation, 0f);
        transform.localRotation = Quaternion.Euler(XBodyRotation, YBodyRotation, 0f);

    }
}
#

still failed the format im sorry T_T @rich ice

rich ice
#

atleast you tried. that's what really matters pensive

#

move down the ``` at the bottom by 1 line

#

should fix it

ashen harness
#

but i think i got it? i just needa know how to connect the X and Y BodyRotation to the controller

verbal dome
#

There we go

ashen harness
#

there we go!

rich ice
#

got there in the end lolCerobaYay

ashen harness
#

but how can i make the (X and Y)BodyRotation be the thing that actually rotates the controller?

#

well the body...

#

but yk what i mean lol

verbal dome
#

What is this script attached to?

#

MouseMovement

rich ice
#

you could make the mesh and the controller separate

ashen harness
#

the camera which is the child of the game object that has the controller

#

you'll see the reference in the script at the top

#

and it's already connected to the game controller

real trellis
#

is there a very particular workflow for creating intro screens, logos and initial loading stuff? otherwise i'm winging it

ashen harness
#

but i needa know how to actually make the controller be the thing getting the rotation from Bodyrotation

rich ice
#

but, you're probably looking for the animator

#

(timeline is also a thing that exists. i dont exactly know what it does. but, it exsits.

last owl
#

Hi, unity noob trying to make a simple game, I have a rocket spaceship that can move left and right and I want the spaceship to rotate 45 degrees to each side as I move. I'm currently using input.getaxis(horizontal) with transform.translate and transform.rotate but the ship continues rotating as I move when I want it to stop at 45 degrees. I've looked up mathf.clamp and eulers and all that but its very confusing. Could someone help me out please?

rich ice
#

is it 2d or 3d?

last owl
#

3D but moves in 2D

#

ship moves upwards on its own and player can only move left and right

rich ice
#

have you tried setting the rotation?

ashen harness
#

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

rich ice
#

so something like

        transform.rotation = Quaternion.Euler(45 * input, 0, 0);
ashen harness
#

lool

last owl
#

whats the difference between transform.rotation and transform.rotate? Unity tutorial uses transform.rotate but everyone else online ive seen uses transform.rotation

rich ice
#

transform.rotate adds to the rotation

#

transform.rotation sets it (and allows you to read it)

pure drift
rich ice
#

transform.forward = rb.velocity.normalized

#

(or atleast thats the quick fix, im still reading the code)

rich ice
pure drift
#

thank you let me try that real quick

ashen harness
#

wait.... theres a simple solution to my problem.....

#

maybe .. we'll find out lmao

pure drift
#

@rich ice i was wondering why my target dissapears when i tried adding this am i doing something wrong

rich ice
#

changing transform.forward should only change the rotation. not position

#

something else must be causing it

pure drift
#

ok ill try changing it thank you

rich ice
static cedar
#

Hi peps. UnityChanwow

rich ice
verbal dome
#

Select it and show us with gizmos in local mode

rich ice
verbal dome
#

If it moves on the XY plane I would expect it to be transform.right or .up

pure drift
#

thank you for the script

ashen harness
#

YOOOooo lets goo i did it lmao

rich ice
#

nice job UnityChanThumbsUp

ashen harness
#

so basically all i did to fix my issue so the body doesn't become parallel to the floor is, the parent which is holds the game controller is the one with the mouse movement for looking side to side and the camera itself is the one that looks up and down

#

probably not the "best" method but if it works then i guess i don't gotta fix it 🤣

#

the reason the body looking straight down was bad was because it made it so when you jumped and walked backwards..... your backwards was in the air....

static cedar
#

I made this stuff using IPointer(Enter, Exit, and Click).
How do i make it so it detects if you clicked something outside of that window (so the dropdown can close)? Preferably by not checking a mouse input every frame.

ashen harness
#

it was a very weird bug lmao

rich ice
ashen harness
#

well it makes sense though in a way

#

cause when you look down, your back is in the air....

#

so moving back... was moving into the air lmao

#

the gravity eventually brought you back down at a speed you couldnt fight but like...

rich ice
ashen harness
#

still being able to jump 2x higher than normal wasn't a great feature lmao

rich ice
rich ice
ashen harness
#

now i coulda just patched the bug with different methods probably

#

but this way is more beginner friendly lmao

static cedar
ashen harness
#

now for the fun part

#

Shift = sprint script lmao

rich ice
#

thought you meant the game window as a whole

ashen harness
#

should be fairly simple just need to refer to the player movement script and increase the player movement score when shift is held down else it is put at it's set value

#

now as for changing values via script from another component is....

static cedar
ashen harness
#

a different issue for me to figure out lol

rich ice
static cedar
#

Oh, it seems like Unity depreciated IPointer stuff. Or it seems like it.

#

Into unity 6.

sonic hull
#

does unity has a function or a solution that allows me to swap runtime animation in animator states? the reason is some others think making a lot of states in animator for different animation clips is unnecessary work basing on their UE experience, so they wonder if they could swap in-out animations in same states to play a lot of different animation in runtime, which is a part for the skill cancel system. overrideController would be a solution but i heard that has a heavy performance hit when used a lot, is there any better approach for such situation?

static cedar
#

Link all animation states to Start and End.
And just use flags.

#

You set the flags in code.
Flags can be vector2, floats, bools.

#

And the condition for each state can be whatever you want.

ashen harness
#

ehh i already ran into an issue 2 lines into coding lmao

sonic hull
#

so must use multiple animator states right

#

there is no way to avoid them

ashen harness
#
        float shift = Input.GetKeyDown(KeyCode.LeftShift);
#

why is it already underlined

#

lmao

static cedar
sonic hull
#

oki, thanks

worn cedar
#

How would I get the player to move with the camera

#

Im using CM freelook rn but I want to move my camera and the player to go twards that way

rich ice
#

use a position constraint or parent the camera to the player

static cedar
#

Is cinemachine good? I never bothered with that.

ashen harness
#
using UnityEngine;

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

    // Update is called once per frame
    void Update()
    {
        float run = Input.GetKeyDown(KeyCode.LeftShift);
        {
            if run = true;
            PlayerMovement.speed = +5;
        }
            

        
    }
}
#

where problem at? xD

rich ice
slender nymph
slender nymph
ashen harness
#

sorta lmao

#
    void Update()
    {
        bool run = Input.GetKeyDown(KeyCode.LeftShift);
        if (run)
        {
            PlayerMovement.speed = PlayerMovement.speed + 5;
        
        }

    }
}```
slender nymph
ashen harness
#

I'll submit to it at some point, been watching a few tutorials and i did start the course but ehh been playing around with 3D movement

verbal dome
#

Is the speed being set every frame?

#

Oh and it's using GetKeyDown so it doesn't even make sense

#

Unless you reset it on keyup

ashen harness
#

that was the start of the code lmao

#

now it's functional

#
        bool run = Input.GetKeyDown(KeyCode.LeftShift);
        if (run)
        {
            PlayerMovement.speed = PlayerMovement.speed + 5;
        
        }
        bool NoRun = Input.GetKeyUp(KeyCode.LeftShift);
        if (NoRun)
        {
            PlayerMovement.speed = PlayerMovement.speed = 15;
        }```
slender nymph
#

PlayerMovement.speed = PlayerMovement.speed = 15;
lol

ashen harness
#

shhhh

#
        bool run = Input.GetKeyDown(KeyCode.LeftShift);
        if (run)
        {
            PlayerMovement.speed = PlayerMovement.speed + 5;
        
        }
        bool NoRun = Input.GetKeyUp(KeyCode.LeftShift);
        if (NoRun)
        {
            PlayerMovement.speed = 15;
        }```
wintry quarry
worn cedar
#

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Transform cameraTransform;

private CharacterController characterController;

void Start()
{
    characterController = GetComponent<CharacterController>();
}

void Update()
{
    float horizontal = Input.GetAxis("Horizontal");
    float vertical = Input.GetAxis("Vertical");
    Vector3 inputDirection = new Vector3(horizontal, 0f, vertical).normalized;

    if (inputDirection.magnitude > 0.1f)
    {
        Vector3 cameraForward = cameraTransform.forward;
        Vector3 cameraRight = cameraTransform.right;

        cameraForward.y = 0f;
        cameraRight.y = 0f;
        cameraForward.Normalize();
        cameraRight.Normalize();

        Vector3 moveDirection = cameraForward * inputDirection.z + cameraRight * inputDirection.x;
        characterController.Move(moveDirection * moveSpeed * Time.deltaTime);

        Quaternion targetRotation = Quaternion.LookRotation(moveDirection);
        transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 10f);
    }
}

}

#

Why isnt this working

slender nymph
#

!code

eternal falconBOT
slender nymph
#

also be more specific than not working

ashen harness
worn cedar
#

It says it needs to derive from monobehavior

ashen harness
#

but it works all the same so hey I'm satisfied lol

wintry quarry
ashen harness
#

lowkey proud i figured out the run ability lmao

ashen harness
#

this is honestly just a learning project i got honestly, just kinda coming up with ideas to slap in and code, learning by doing which ultimately probably isn't the best method with all these courses and stuff but I wanna just kinda play around with some coding and figure it out the hard way lmao if something doesnt work i search it up ig

vocal junco
#

yo i just had a weird thing happen
i added something relatively small that should have just saved a text based on an outcome (win or loss) of my gamescene using PlayerPrefs, and then used that to set a text in the gameover scene

and it proceded to not let me play my gamescene, every time i press the play button unity just freezes and stops responding so i have to close it with the task manager

i tried deleting that script (and a bunch of others that were my most recent to try work back to the issue)
but it hasnt done anything its still freezing, and now ive lost scripts for no particular reason

would anyone have any ideas to fix, or any questions i could try to answer to help narrow down a solution?
please im desperate

wintry quarry
vocal junco
#

it was a few hours ago at this point so im not sure exactly the order of things i added but i have a general idea and have removed pretty much everything ive added today, and everything from previously was working fine

wintry quarry
#

check the newly added code for while or for loops

vocal junco
#

damn it

wintry quarry
#

yep you wrote an infinite loop 😛

vocal junco
#

i forgot about that one actually

#

thank you!

wintry quarry
#

Why does your class derive from PlayerInput?

#

No, the class should not be static

#

just the instance

#

Because you made the instance variable of type PlayrerINput

#

If it's not derived from MonoBehaviour it won't be a component

#

You want something like this:

public class MySingletonThing : MonoBehaviour {
  public static MySingletonThing instance { get; private set; }

  public readonly PlayerInput input = new();

  void Awake() {
    instance = this;
  }
}```
#

Technically not really no

#

But you couldn't use Awake in that case

#

You could do something along these lines:

public class MyInputHolder {
  static MyInputHolder _instance;
  public static MyInputHolder Instance {
    get {
      if (_instance == null) {
        _instance = new();
      }

      return _instance;
    }
  }

  public PlayerInput Input { get; private set; } = new();
}```
#

yes

wintry quarry
#

It's not better it's different

#

It does mean you wouldn't have to put it in the scene though

#

But you would need to manage eveything about its lifecycle manually

#

This is more of a typical plain C# singleton

#

vs a Unity singleton

#

it's short for new PlayerInput() yes

#

it's called a target-typed new

#

what part gives you what error

#

You seem to be accessing playerInput in OnEnable before it's assigned

#

just based on that screenshot

#

OnEnable runs before Start

#

You could use OnEnable, you just can't use the variable before you assign it

#

Ok so you're using the MonoBehaviour way

#

Rule of thumb here is that you should not access other components in Awake or OnEnable

#

because there's no guaranteed order for that

#

gInput's Awake is running after the other script's

#

Did you actually put an instance of gInput in the scene?

#

yes

#

It needs to be attached to a GameObject in the scene

#

That's... a weird setup, to be honest

#

but you'd have to show the whole setup

#

These errors seem to be in a different script

#

Oh yeah this:

    public static gInput instance { get; private set; }
    public readonly PlayerInput input = new();
    void Awake()
    {
        instance = this;
    }```
Should be changed to:
```cs
    public static gInput instance { get; private set; }
    public PlayerInput input { get; private set; }
    void Awake()
    {
        input = new();
        instance = this;
    }```
#

this will fix the first error, and the first error was causing the instance not to get assigned I would say

cosmic dagger
#

that's usually how it's done. you can have a separate GameObject for each singleton or pile them all on the same one. using a separate GameObject for each gives you more freedom and ease of setup, design-wise . . .

gray cairn
#

@cosmic dagger can I ask you a question

cosmic dagger
#

though, it's easier to just ask the chat bcuz anyone could help answer . . .

rich adder
gray cairn
#

Oh I’m sorry I’m just really new to this whole thing and everytime I go to load a project it says failed to decompress template and it won’t load I have tried moving the path file so it wasn’t so long and I deleted and redownloaded unity 4 times tonight trying to get it to work

rich adder
#

and probably check the logs

gray cairn
#

What do you mean @rich adder

rich adder
gray cairn
#

I’m like brand new got unity today I just have a game idea I wanna make it’s super simple

gray cairn
#

Yes obviously but not for game development

rich adder
#

but what I suggested has nothing to do with game development

gray cairn
#

Wym lol isn’t that everything unity is lol

rich adder
#

checking if you have enough disk size on pc is a basic usage of computer

gray cairn
#

I mean I have a 1tb hard drive? I’m not very tech savvy

rich adder
#

since you asked what do you mean, thats why I asked lol

rich adder
gray cairn
#

I have a very specific idea that I want to emulate an old toy from the early 2000s called cube world I want to make a modern version for computer and 337 gigs free

rich adder
#

it would help if you showed details rather than having to ask 20 qs

gray cairn
#

Do you remember that toy by chance looks like this

#

I’ll show you a picture of what it is doing one sec

#

Sorry it’s going to make me reinstall the editor hopefully that fixes it

teal viper
# gray cairn

Might want to upload an image of a common format like Jpeg or PNG that are displayed in the discord. No one is gonna download that file to have a look

gray cairn
#

Oh my bad I didn’t know it was like that lol one sec

#

I was wondering why it was like that

#

It’s a super simple concept one stick figure per cube when cubes are connected stick figures can flow in between them and each cube has a unique character action and appearance

#

How would you code something like that

rich adder
#

there are quite a few systems involved

#

probably should not be your first project if you're new lol

#

start with basic projects to gain xp, and with unity learn website lessons

gray cairn
#

But it is like the one thing I wanna do lol cause I have not found anyone who has emulated this toy lol and I just wanna play it again and live out the nostalgia

#

Like I’m just trying to do this for a personal thing

teal viper
#

It's also not entirely clear how you want to implement it. Are you gonna need these cubes(or an upgraded version of them) to run the game?

rich adder
#

yeah the idea sounds good, no one saying dont go for it, just build up the mechanics to it by learning smaller things

#

games are just a bunch of systems mushed together

gray cairn
#

No no I want it to be like a fallout shelter lay out game @teal viper where you can stack them like rooms

#

I want it to be a digital game not a physical toy

rich adder
#

yeah you'd need to make the rooms and have anchor points on each part of the wall

gray cairn
#

Well @rich adder how would you suggest I get on the path to build that type of game what kind of basics should I know

rich adder
eternal falconBOT
#

:teacher: Unity Learn ↗

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

rich adder
#

the pathways gets you going learning basics like positions, transforms and other components important to code what you want

gray cairn
#

Fair do you remember that toy @rich adder by chance

rich adder
gray cairn
#

@rich adder that is another thing I was thinking about doing but I’m not sure if it envolves unity to try and put emulated games on my gameboy sp

rich adder
#

but yeah does look like it uses some type of magnets/connectors to link the cubes

gray cairn
#

Really the games are so expensive now

#

@rich adder would you possibly be willing to help me

#

With the game once I learn some stuff

rich adder
#

you can try in !collab

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

gray cairn
#

Fair that makes sense I honestly am hoping I can get this done I know I can make all the animation for it I just gotta figure out how to run it in a game

rich adder
#

well thats what learning the tool is for 🙂

static cedar
gray cairn
#

Yep hahah I can’t even get the editor to install now

#

It’s doing this then failing to validate? @rich adder

rich adder
#

also this isn't code question

gray cairn
#

Ok I’m sorry

sacred cradle
#

hello, is there a way to instantiate an object directly from the assets instead of making a prefab and assigning that as a variable?

charred spoke
#

Either use Resources or Addressables

sacred cradle
#

how do i do that?

charred spoke
#

Google it

sacred cradle
#

i did already

#

so i came here for help

#

not to google something i already know

charred spoke
#

Well what did you try? What did not work? How does your code look like?

sacred cradle
#

i followed this

#

and it did not work

charred spoke
#

That code seems valid to me

#

What did not work exactly ?

sacred cradle
#

hold on

#

nevermind

#

it was my ide

#

allgood 👍

#

thanks anyways

#

i have another issue now..

#

when casting my ray, its returning the position of the object it hit

burnt vapor
sacred cradle
sacred cradle
#

ty

burnt vapor
sacred cradle
#

yes

#

100%

#

it works, ty :DDDDD

signal pollen
#

Hello. I want to be able to send data between one object (the truck) to another (the drop off location or the crate). How would I go about doing that through scripts?
Data may be like on the lines of "Hey, you've gained one crate" or "Hey you have been picked up"

teal viper
#

The basics of the basics

signal pollen
#

Is there a tutorial on this?

teal viper
eternal falconBOT
#

:teacher: Unity Learn ↗

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

teal viper
#

As they cover this and many other basics that you need to know to get started.

signal pollen
#

Hmm okay. I have been following the junior course, maybe I missed a step or forgotten something

visual linden
#

You'll get there :) Starting out with Unity there's so much ground to cover and it definitely takes a while for it all to sink in.

teal viper
signal pollen
#

https://learn.unity.com/tutorial/lab-1-personal-project-plan?uv=2022.3&projectId=5caccdfbedbc2a3cef0efe63 Following this course, I am on Lab 1, trying to make this mini game. I don't feel like I covered referencing in the Lesson 1.1 to 1.4 with their car and plane thingy. It was mostly collision boxes

Unity Learn

Overview: In this first ever Lab session, you will begin the preliminary work required to successfully create a personal project in this course. First, you’ll learn what a personal project is, what the goals for it are, and what the potential limitations are. Then you will take the time to come up with an idea and outline it in detail in your D...

#

Yeah, reviewing it, Unit 1 does not cover referencing

#

If the solution is to stop this mini-project, continue the course to learn more, and then come back to it, I guess I should do that

visual linden
signal pollen
#

Alright then. I will do that. Thanks.

visual linden
#

But playing around on your own in-between the courses to figure out where you are on your learning path is definitely a good idea

signal pollen
#

The thing is the "I don't know what I don't know" that is kicking my butt

#

Like earlier, I found out through asking here about wheel colliders.

#

I will have a better look at the course syllabus overview, maybe that will guide me better.

teal viper
#

The essentials are more to teach you to work with the editor if I understand correctly.

signal pollen
#

I see! The lab work looked to me as if it's a "Go off an do a thing". I did try that not realising that I should have kept within the parameters of what was taught.

teal viper
#

The final goal is that you would know where(in the manual/API docs) and what to look for when you need to learn about a feature or implement one.

signal pollen
#

farlynnotes Thanks again! I will do the tutorials. It appears that Unit 2 and 4 of the Jr. Pathway covers what I need.

dark flare
#

Hello! I'm getting a strange visual error that could use some help. I'm using 3d drag and drop but the z position keeps changing during the drag part, it looks like it flickers between 10 and zero. I've tryed to set z to zero but that made it even worse. Is there a problem with this script?

using Unity.VisualScripting;
using UnityEngine;

public class Draggable : MonoBehaviour
{
    private Vector3 mousePositionOffset;
    [SerializeField] private Camera m_Camera;
    [SerializeField] private Vector3 originalPosition;
    [SerializeField] private Vector3 draggingPosition;
    [SerializeField] private Vector3 finalPosition;
    [SerializeField] private bool backAtStart = true;
    [SerializeField] private bool dragging = false;
    public bool dragable = false;
    private float elapsedTime = 0;


    private void Awake()
    {
        m_Camera = FindFirstObjectByType<Camera>();
    }

    private Vector3 GetMouseWorldPosition()
    {
        return m_Camera.WorldToScreenPoint(gameObject.transform.position);
    }

    private void OnMouseDown()
    {
        if (!backAtStart || !dragable) return;
        originalPosition = gameObject.transform.position;
    }

    private void OnMouseDrag()
    {
        if (!dragable) return;
        dragging = true;
        gameObject.transform.position = m_Camera.ScreenToWorldPoint(Input.mousePosition - GetMouseWorldPosition());
    }

    private void OnMouseUp()
    {
        if (!dragable) return;
        finalPosition = gameObject.transform.position;
        dragging = false;
        if (finalPosition != originalPosition)
        {
            backAtStart = false;
            StartCoroutine(ReturnToStart(1f));
        }
    }
    IEnumerator ReturnToStart(float waitTime)
    {
        while (elapsedTime < waitTime)
        {
            gameObject.transform.position = Vector3.Lerp(finalPosition, originalPosition, (elapsedTime / waitTime));
            elapsedTime += Time.deltaTime;

            yield return null;
        }

        elapsedTime = 0;
        backAtStart = true;
        transform.position = originalPosition;
        yield return null;
    }

}```
timber tide
#

I'mma go with you'd probably dont want to be dragging the cards in world space

#

gameObject.transform.position = m_Camera.ScreenToWorldPoint(Input.mousePosition - GetMouseWorldPosition());
Are you zeroing out the z here? That's a bandaid you can do probably

languid spire
eternal falconBOT
dark flare
# timber tide ```gameObject.transform.position = m_Camera.ScreenToWorldPoint(Input.mousePositi...

Thanks for the input! I've tried to play around with the z axis in that line, but it makes it worse. I've tried : cs //gameObject.transform.position = m_Camera.ScreenToWorldPoint(Input.mousePosition - GetMouseWorldPosition()); draggingPosition = m_Camera.ScreenToWorldPoint(Input.mousePosition - GetMouseWorldPosition()); //gameObject.transform.position = new Vector3(draggingPosition.x, draggingPosition.y, originalPosition.z); //gameObject.transform.position = new Vector3(draggingPosition.x, draggingPosition.y, transform.parent.position.z); gameObject.transform.position = new Vector3(draggingPosition.x, draggingPosition.y, -5f);

timber tide
timber tide
#

assuming you are working with rect transforms

#

Otherwise you can probably add a transparent quad in the background with a collider to define yourself a plane if this is all in world space. Though, zero-ing the z should work fine so if you can figure out what's causing the issues with it.

fringe plover
#

How do i reference AudioRandomContainer in code? (no i dont need AudioResource)

#

Like, scripting API doesnt even have it

rich ice
#
Unity Learn

This tutorial will guide you through creating and configuring an Audio Random Container in the Unity Editor, a key tool for dynamic audio experiences. You'll discover how to add multiple audio clips to the container and set them up for randomized playback. Additionally, you’ll delve into the various Trigger modes and learn how to manage these au...

crystal quiver
#

Guys pls help where can i learn c# oop

#

I cant find anything

rich ice
#

!cs

eternal falconBOT
rich ice
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

languid spire
rich ice
#
#

!code

eternal falconBOT
viscid fable
rich ice
quick pollen
#

so you can't do this?

grand snow
#

The error squiggles are cus you forgot break;

rich ice
quick pollen
#

I know I don't have breaks

grand snow
#

you can however do this safely:

switch(blah)
{
  case 1:
  case 2:
    break;

  default:
    break;
}
quick pollen
#

can i not have anything after case 1?

#

like to do something?

grand snow
#
  case 1:
  case 2:
  Debug.Log("I log on 1 AND 2")
    break;
night raptor
quick pollen
#

what if I want something for case 1?

#

ahh okay

grand snow
#

then add something but you cannot do the fall through anymore

quick pollen
#

thats sad

grand snow
#

if you need more complex checks you just need to go back to if else

quick pollen
#

I guess I can do this?

#

if theres no errors, exit the method

#

if theres any kind of error, log it, and do the last 2 instructions

burnt vapor
#

Except in the previous code you shared those last two lines only happened in case 3

night raptor
burnt vapor
#

If the whole point is to log a message and to ensure case 0 is not handled, then just write it in steps rather than introducing a switch

burnt vapor
#
var result = RecalculationConditions();
if (result == 0) return;
var message = result switch
{
  1 => "Foo",
  2 => "Bar",
  _ => "Baz",
};
Debug.Log(message);
agent.destination = ...
#

I assume Unity has inline switches by now?

quick pollen
crystal quiver
#

object oriented programming

quick pollen
rich ice
eternal falconBOT
#

:teacher: Unity Learn ↗

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

burnt vapor
#

Even better would be to cache the strings, or put them in an array. Then you can access it from the index of result

rich ice
#
Unity Learn

In this mission, you’ll refactor the inventory project you completed in the previous mission using the pillars of object-oriented programming as a guide. You’ll deep dive into the inner workings of each pillar individually, so you can better understand its value in developing applications. Next, you’ll learn how to profile your code to identify ...

quick pollen
#

I mean, the way I did it should be fine tho no?

#

the last one

#

btw yes this is for pathfinding

burnt vapor
# quick pollen oh yeah I see
// Somethere at the start of the class.
private static readonly string[] _resultMessages = [
  "Foo", "Bar", "Baz"
];

var result = RecalculationConditions();
if (result == 0) return;
Debug.Log(result - 1); // Index starts at 0
agent.destination = ...
burnt vapor
quick pollen
burnt vapor
#

Then use the array, otherwise you are constantly making strings

quick pollen
#

oh

burnt vapor
#

This also depends on how often the code is called though. If it's not frequent, it does not matter

quick pollen
#

my idea is that I'm generating random points to wander towards

#

if the distance from the point is too big, or the status is invalid (tho im not even sure that helps) or the character doesnt move for a specific amount of time, I want to recalculate

#

I'm using Random.insideUnitCircle, which can generate points inside walls or outside the game field

#

I couldn't find a better way to check if the point that the agent is trying to move towards is actually accessible

burnt vapor
#

But I am more than happy to help with general C#

rich ice
#

i think audioRandomContainer is more like a scriptable object

#

you aren't supposted to change it at runtime

#

thus is why you dont need access to it

#

(im probably wrong though, i haven't used it before)

fringe plover
#

I just need to access list of audio clips, bruh, even scriptable objects are accessable, could have just made them { get; private set }

wintry quarry
#

Is that your custom class?

fringe plover
#

no

wintry quarry
#

What are you trying to do

fringe plover
rich ice
#

why not just make a seperate list?

wintry quarry
grand snow
fringe plover
# wintry quarry In order to do what

I preload AudioClip's in loading screen, i have list, but instead of manulaly putting every audio clip in Container , i wanted to use AudioRandomContainer

burnt vapor
#

There are also questions that generally revolve around C#

wintry quarry
quick pollen
#

welll....

#

tbf C# is in Unity, so

leaden pasture
fringe plover
burnt vapor
# quick pollen welll....

Then your question from a few minutes ago would not apply here since you were asking about C# syntax which has nothing to do with Unity

fringe plover
#

Okay i guess ill just make audio data preload at start

burnt vapor
fringe plover
quick pollen
rich ice
quick pollen
leaden pasture
static cedar
#

I'm using IPointerClick, is there a way to have the event continue to propagate up even if one script already catches it?

burnt vapor
leaden pasture
#

Valid 😭

wintry quarry
wintry quarry
#

Or something with the Use and used property?

burnt vapor
#

You come here asking coding questions and the majority often do not involve Unity

#

I don't see why it matters anyway

grand snow
#

I guess it doesn't, anyone here is free to step in to help when they can help (general c# or unity specific)

static cedar
burnt vapor
#

And if I am not experienced with it, I don't help with it

grand snow
#

as long as you are aware of other unity specific gotchas and limitations

#

like how old our c# version is 😭

static cedar
wintry quarry
burnt vapor
#

.NET Standard 2.1 is the latest version and Unity runs on it since 2021.2

grand snow
#

no it has the feature set of something around c# 6/7 so its lacking certain features
probably due to the use of mono and not the .net core clr

runic lance
#

it's pretty old, we have only a subset of C# 9 features

#

the current version is 13 already

grand snow
#

Hopefully in this year we actually get the promised updates 🙏

static cedar
#

Unity 6 allowed file scope namespace even though it's still Standard.
Is there a reason why we can't use newer C# syntax even with older C# versions way before that?

#

Seems like I can do C#10 syntax in a .NET Standard in a normal project.

grand snow
#

I presume because mono or whatever else unity has modified or slapped on

burnt vapor
#

I would not call that old

#

When it migrates to CoreCLR it probably supports the latest version

static cedar
#

Of course we can't really use actual newer C# features like record structs. Whatever actual means.
Also other new standard library functions or optimisations, mostly Linq for the latter i think.
These aren't available even if we made the C# syntax to match newer versions.

static cedar
burnt vapor
#

As in you can't modify to an older one?

#

I don't know how strict Unity handles the csproj files, but I would assume you can just modify it?

swift crag
#

to be honest, I don't understand the relationship between Mono/CoreCLR, the version of .NET, and the version of C#

static cedar
#

Unity rewrites csproj files every build.

#

I wish they just stop doing that.

swift crag
#

I think that's the idea?

burnt vapor
static cedar
#

Once they do switch to CoreCLR, I also wish they would just allow standard csproj. I feel like the Assembly Definition files are kinda wonky. But I also have a feeling they won't because they would rather keep controlling properties in the Unity editor.

burnt vapor
#

csproj files are super useful

pure fractal
#

Can Unity make Turn based game? if yes Do you suggestion tutorial pls

burnt vapor
cosmic dagger
brave compass
static cedar
brave compass
static cedar
#

Ah. UnityChanwow

brave compass
#

MSBuild Integration and Convergence
We’re making progress on fully integrating MSBuild between Unity’s internal build pipeline (for UnityEngine modules) and the user code compilation pipeline. This convergence will lead to a more streamlined and optimized workflow.

A key benefit of MSBuild integration is an improved IDE experience. In the past, building from the IDE didn’t use the same compilation pipeline as Unity, which could lead to inconsistencies. With MSBuild integration, we’ll share the same pipeline, ensuring the IDE build process is reliable.

MSBuild will also bring a major upgrade by standardizing the C# compilation pipeline, including support for NuGet packages. Another advantage is the extensibility of MSBuild, allowing developers to customize the managed code build process more easily.
https://discussions.unity.com/t/coreclr-and-net-modernization-unite-2024/1519272

swift crag
#

Exciting!

static cedar
#

Btw, how can you copy parent component values and paste it on an inheriting component?

#

The option's grayed out.

verbal dome
#

You would think that it's possible but apparently not 🤔

static cedar
#

Yeah it's.

#

Wild.

swift crag
#

but I forget how to actually edit the copied component (you can't paste it externally and when copy it back in, annoyingly)

static cedar
#

Found out that Awake does not guarantee to be the first event called across all game objects.
It's mixed with OnEnabled.

visual linden
frail hawk
#

i was about to say same

visual linden
#

Maybe they mean 2 gameobjects in the scene are not guaranteed to have the calls invoked in unison?
eg Awake-> OnEnable might be called for gameobject 1 before Awake->OnEnable is called for gameobject 2

brave compass
#

Awake is always called before OnEnable on each script, but for an entire scene, it gets initialized as:
object1.Awake
object1.OnEnable
object2.Awake
object2.OnEnable

Instead of:
object1.Awake
object2.Awake
object1.OnEnable
object2.OnEnable.

burnt vapor
#

OnEnable happens when the instance of the MonoBehaviour is created, which is just after Awake

#

You might be confused with how Unity handles the lifecycle when it first loads a scene vs when you add concurrent gameobjects @static cedar

edgy tangle
brave compass
edgy tangle
#

Right I’m aware

#

But I mean in terms of entire scene execution

#

I always thought it was:
All monos - Awake
All monos - OnEnable
All monos - Start

#

Of course it needs to iterate through each one during each phase so getting references to things all in awake isn’t going to work often

#

Which is why sometimes its better to do it in start

#

Because for sure what happens is any Start will occur after all Awakes

swift crag
#

Awake and OnEnable run on each object in the scene on frame 0.

#

Start then runs on every object on frame 1.

brave compass
# edgy tangle But I mean in terms of entire scene execution

The entire execution with Start and Update would be ordered like this:

Scene load:
object1.Awake
object1.OnEnable
object2.Awake
object2.OnEnable

First Update
object1.Start
object2.Start
object1.Update
object2.Update

Subsequent updates
object1.Update
object2.Update

edgy tangle
#

Okay interesting. I never knew this

swift crag
#

Also, every Start method on a certain frame runs before every Update method on the same frame

dark flare
#

Hello, I'm looking for help with a script that I've tried in multiple projects and scenes, but it still behaves the same way. The issue is that some seemingly random value is thrown into my drag value making the dragged object appear ofscreen half the time. it also makes the movement appear to move at half the speed of the mouse. Please take a look at this script in one of your scenes and help me find what is wrong.
https://paste.mod.gg/duygzyexnuoo/0

brave compass
swift crag
swift crag
dark flare
swift crag
#

GetMouseWorldPosition is named wrongly. It should be GetCardScreenPosition

brave compass
swift crag
#

Given how the card looks like it's flying out of the camera, I think the card is getting moved on the Z axis

#

Do you have a perspective camera?

#

Even if it's orthographic, this part is very suspicious:

gameObject.transform.position = m_Camera.ScreenToWorldPoint(Input.mousePosition - GetMouseWorldPosition());

#

ScreenToWorldPoint needs a Z position to know how far from the camera the point should be

grand snow
#

for keeping movement on a plane i use screen point to ray and then i use a Plane cast

swift crag
#

Oh yeah, that's exactly the problem

swift crag
grand snow
#
Plane dragPlane; //Your plane
public void OnDrag(PointerEventData eventData)
{
    var dragPosRay = eventData.pressEventCamera.ScreenPointToRay(eventData.position);
    if (dragPlane.Raycast(dragPosRay, out float hitDistance))
    {
        Vector3 newPosition = dragPosRay.origin + (dragPosRay.direction * hitDistance);
        transform.position = newPosition;
    }
}

an example via the event system

swift crag
#

Therefore, ScreenToWorldPoint will give you a point behind the camera

#

It'll flip-flop back and forth every single frame

#

(also, Plane is straightforward to create -- you give it a point the plane should go through and the normal vector, which is the direction the plane is facing)

#

So you'd make a plane that:

  • Goes through the original position of the card
  • Faces the camera
dark flare
robust harness
#

is this the right way to go about this, it seems very dumb (the code is in a state machine so i cant make the gameobjects public) ```csharp
private GameObject playerPrefab;
private GameObject enemyPrefab;
private Transform playerBattleStation;
private Transform enemyBattleStation;
private TextMeshProUGUI playerName;
private TextMeshProUGUI enemyName;

private Unit playerUnit;
private Unit enemyUnit;

public override void EnterState(BattleStateManager battle)
{
    playerPrefab = battle.GetComponent<BattleStateManager>().playerPrefab;
    enemyPrefab = battle.GetComponent<BattleStateManager>().enemyPrefab;
    playerBattleStation = battle.GetComponent<BattleStateManager>().playerBattleStation;
    enemyBattleStation = battle.GetComponent<BattleStateManager>().enemyBattleStation;
    playerName = battle.GetComponent<BattleStateManager>().playerName;
    enemyName = battle.GetComponent<BattleStateManager>().enemyName;

    SetupBattle();
    Debug.Log("Initializing battle");
}```
swift crag
#

You can reference prefabs by a component type

#

I almost never reference prefabs as GameObjects

#

also, you already have a BattleStateManager

hot laurel