#💻┃code-beginner

1 messages · Page 59 of 1

polar acorn
#

Un-delete it

#

The event system is what makes your UI events work

solemn bobcat
#

Most likely the issue is unrelated to this code. Probably you're missing EventSystem component (which is necessary for all UIs on scene to work) or some other object is in front of your button (which blocks raycasts and access to the button).

polar acorn
#

It has nothing to do with Visual Scripting

swift crag
#

That's what I originally thought the problem was -- that it wasn't partially masking the text

#

but I'm a little unclear on what the issue is..

pliant oyster
#

Thank you!

vocal fable
#

is there any way to make rocket jumping like in tf2

#

or quake

vocal fable
#

thanks

swift crag
#

I never actually knew about that until recently

#

I just did it manually with an OverlapSphere

polar acorn
swift crag
#

true; this just does a little extra math for you

white crag
#

i remember your name from 3 years ago

polar acorn
white crag
#

have you made any games

polar acorn
white crag
#

how come ;(

polar acorn
#

They keep adding new stuff to Runescape

white crag
#

hahahahaha

white crag
#

people say making games ruins the magic of playing them

swift crag
white crag
#

now I cannot play a single player game ever again

polar acorn
#

Just added new bosses to it recently actually

swift crag
swift crag
#

unfortunately i am no longer a small child and have trouble playing games non-efficiently

white crag
#

i cannot see a cool indie game without the burning desire of making it which wont go away until i try

eternal needle
# white crag people say making games ruins the magic of playing them

For me it's the opposite, i always played games trying to break apart how things work. I cant imagine many scenarios where someone learns how an effect is made, then doesnt wanna play a whole game because they know fire is now just a particle systen and not real fire in their monitor

white crag
#

for me its just that I wasnt ever a single player game type of guy

#

and even though I have a big passion for seeing how cool alot of indie games are I still dont enjoy any single player game except like assassins creed but even that I cant come to enjoy anymorer

#

im still very intrigued by all types of games though and rather watch someone play them than play them myself for some reason

halcyon mauve
#

I am trying to make a spawn manager script that randomly picks from one of three prefab models, where should I start?

swift crag
#

Make a list of game objects. Pick a random number that's less than the length of the list.

#

If you have a more specific component on all of the prefabs, you should make a list of those instead

#

so, for example..

#
[SerializeField] List<Bullet> bullets;

void Start() {
  int index = Random.Range(0, bullets.Count);
  Bullet newBullet = Instantiate(bullets[index]);
}
tall delta
swift crag
#

this would work if all of my prefabs had a Bullet on them

halcyon mauve
#

Yeah I have created around 4 prefabs made in a prefab folder for the project and need one of them to be spawned in randomly in a random direction

#

So I trying to understand how to put that in a script

ivory bobcat
halcyon mauve
#

So I guess my question for that would be how do I get the script to have the prefabs as targets

#

Like how to I have them as objects in the script

tall delta
swift crag
#

simex's answer will let you do that.

#

A List<GameObject> will show up in the inspector.

#

You can drag the prefabs into it.

ivory bobcat
#

Are you simply stuck on implementation of code?

#

If so, maybe check out the tutorials pinned on this channel UnityChanThink

halcyon mauve
#

A little bit yeah

#

Ok I think I am getting it. So the list is open-ended but in Unity you can drag the objects you want in the list to the script?

#

If I wanted them spawned ever 0.5 seconds is that in the Update method?

swift crag
#

The easiest way would be to use a coroutine.

ivory bobcat
#

Are you finished with the referencing of objects first?

tall delta
#

I'd break this down in to simple steps, all off these should be simple to google. or maybe even ask here

  1. Learn how to spawn a prefab.
  2. Learn how to spawn a list of prefabs.
  3. Learn how to spawn just one item from a list of prefabs.
  4. Learn how to select a random element from a list, then spawn that.
  5. Learn how to move an object that has been spawn by code.
  6. Learn how to create a random movement.
swift crag
#

But yes, get that done first.

#

Worry about spawning many objects after you can spawn one object

halcyon mauve
#

This is what I have:

public class SpawnManagerA : MonoBehaviour {
public List<GameObject> listofPrefabs;

// Start is called before the first frame update
void Start() {
    
}

// Update is called once per frame
void Update() {
    var randomPrefab = listOfPrefabs[Random.Range(0, listOfPrefabs.Count())]
    
}

}

swift crag
#

Looks good.

#

This will get a random prefab every frame.

#

It won't do anything with it, of course.

halcyon mauve
#

OK Thanks

wintry quarry
#

it's just listOfPrefabs.Count not listOfPrefabs.Count()

halcyon mauve
#

So I am trying to add the script to an empty game object but I keep getting this error:

Can't add script component 'SpawnManagerA' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.

swift crag
#

well, have you checked for the problems the message is talking about?

#

you must have zero errors in the console

#

including errors for other scripts

polar acorn
halcyon mauve
#

The names match

polar acorn
halcyon mauve
#

I have no errors so far, at least that is what Visual Studio is saying

halcyon mauve
#

I dont know how to compile it on unity tbh

swift crag
#

Unity will try to compile your code whenever it sees changes.

#

If it has any problems, it will put errors in the console.

#

Look at the console.

halcyon mauve
#

It saying nothing

swift crag
#

Screenshot the entire console and show us.

polar acorn
halcyon mauve
#

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

public class SpawnManagerA : MonoBehaviour {
public List<GameObject> listofPrefabs;
public char 'c';

// Start is called before the first frame update
void Start() {
    
}

// Update is called once per frame
void Update() {
    var randomPrefab = listOfPrefabs[Random.Range(0, listOfPrefabs.Count)]
    
}

}

polar acorn
eternal falconBOT
swift crag
#

that will not compile.

#

Screenshot your console.

halcyon mauve
#

Ah ok I didnt know how to format that sorry

swift crag
#

that line is malformed, yes

tall delta
#

I might be a bit off base here, but it seems to me like you'd get a lot out of a quick "how to unity" tutorial. something like this: https://www.youtube.com/watch?v=j48LtUkZRjU&list=PLPV2KyIb3jR5QFsefuO2RlAgWEz6EvVi6

it's just that, yes, people here could just give you the copy / paste code that does what you want. but it's kind of like asking:
what's the answer to ∫(2x^2 + 3x + 1) dx
and you get: answer is (2/3)x^3 + (3/2)x^2 + x + C

it doesn't really help anything, if you don't understand the question, or the answer 😅 because you don't learn anything that way

Want to make a video game but don't know where to start? This video should help point you in the right direction!

♥ Support my videos on Patreon: http://patreon.com/brackeys/

····················································································

This video is the first in a mini-series on making your first game.

···············...

▶ Play video
ivory bobcat
halcyon mauve
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnManagerA : MonoBehaviour {
    public List<GameObject> listofPrefabs;

    // Start is called before the first frame update
    void Start() {
        
    }

    // Update is called once per frame
    void Update() {
        var randomPrefab = listOfPrefabs[Random.Range(0, listOfPrefabs.Count)]
        
    }
}
swift crag
polar acorn
summer stump
#

I recommend a c# tutorial like:
https://www.w3schools.com/cs/index.php
Personally I found a pure c# tutorial more helpful than a unity-specific one

There are also other resources in the pins of this channel

summer stump
halcyon mauve
#

This is the consol. It has nothing at all because I dont have the spawn manager as a component to anything yet

swift crag
#

You have errors hidden.

summer stump
swift crag
#

Click that button to show them.

summer stump
halcyon mauve
#

Semicolons

swift crag
#

🫠

halcyon mauve
#

Sorry about that

coral vapor
#

Can someone help me, I’m trying to make a mobile runner game and I can’t find the template for it on my editor

summer stump
ivory bobcat
#

You should be able to find Unity official templates on the asset store as well.

halcyon mauve
#

I think this is the main problem but IDK what that means

polar acorn
halcyon mauve
#

Is it conflicting with a move forward script then? it has a start and update method in it as well

summer stump
slender nymph
halcyon mauve
#

Ah ok

#

this was the first spawn manager script though

slender nymph
#

if you are using vs code and you moved or renamed the file then hit save in vs code again then you just recreated the same file that you originally moved/renamed

summer stump
halcyon mauve
#

So I have to go digging then I guess

swift crag
#

i do it occasionally

#

Just search for project for "SpawnManagerA" and you'll find the duplicate.

#

ctrl-shift-F in VSCode, at least.

tall delta
slender nymph
# swift crag it's a very easy mistake to make

i honestly prefer visual studio's method of handling changes to files. it tells you the file you were editing no longer exists and basically forces you to open it again. very handy to prevent accidentally duplicating something when you've moved or renamed it inside of unity/filesystem instead of using the refactoring tools in VS

slender nymph
halcyon mauve
#

Ok I fixed the dupilicate problem. Now it says that prefabList does not exist in current context

summer stump
#

Not prefabList

swift crag
#

well, yes, you didn't name the field prefabList

halcyon mauve
#

Sorry was just typing that not that it was the correct name

#

the error does say listOfPrefabs my bad

summer stump
#

Trying to use it outside of SpawnManagerA without a proper reference?
Show the code where the error is

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

public class SpawnManagerA : MonoBehaviour {
    public List<GameObject> listofPrefabs;

    // Start is called before the first frame update
    void Start() {
        
    }

    // Update is called once per frame
    void Update() {
        var randomPrefab = listOfPrefabs[Random.Range(0, listOfPrefabs.Count)];
        
    }
}
swift crag
polar acorn
# halcyon mauve

You should use things that exist instead of things that do not

slender nymph
eternal falconBOT
swift crag
#

you know, this code editor probably isn't configured

#

given all of these typos

coral vapor
halcyon mauve
#

Sorry I have three classes this year using java, c#, and c and I am constantly having to change it. C# is completely new to me but its not too bad

slender nymph
#

Java and C also require you to spell things correctly

summer stump
#

At least that's how it is for me when I jump between languages

coral vapor
#

Is Computer science a major I should go for in college cause I heard it’s a job that there is gonna be too much coders for in the next 6 years

halcyon mauve
swift crag
slender nymph
swift crag
#

so yes

#

configure your IDE

coral vapor
wintry quarry
swift crag
#

the longer you spend here explaining why you aren't fixing your code editor, the longer it will take to help you

#

so go do it

summer stump
coral vapor
#

Would that not work

summer stump
coral vapor
#

Can’t find mobile runner game template for tutorial in asset store, do I have to download 2021 editor version

coral vapor
tall delta
trail gull
#

In my script im making 2 gameobjects called leftcurrentBox and rightcurrentBox
Im trying to destroy them when they come into contact with my gameobject called 'Destroyer'

    void OnTriggerEnter(Collider other)
    {
        if (other.TryGetComponent<Destroyer>(out Destroyer destroyer))
        {
            Destroy(leftcurrentBox);
            Destroy(rightcurrentBox);

This is my code but its not working and the two gameobjects just go through the 3d object
My destroyer gameobject has trigger on, has a script attached to it

slender nymph
#

does your gameobject that is called Destroyer also have a Destroyer component attached? and have you confirmed that this code is even running?

trail gull
#

A Destroyer component?

tall delta
hollow axle
#

How do you write classes? I want to make a Traits class and pass the parameters. Currently I have it like this which of course is wrong:

public class Traits
    {
        public float Speed;
        public int[] Color;
        public float[] Scale;

        // Constructor for Traits class
        public Traits(float speed, int[] color, float[] scale)
        {
            Speed = speed;
            Color = color;
            Scale = scale;
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        public Traits balltTraits = new Traits(1.0f, {255,0,0}, {0.5f,0.5f});
        //gameObject.GetComponent<Image>().color = new Color(255,0,0);
    }
slender nymph
wintry quarry
summer stump
tall delta
swift crag
summer stump
swift crag
#

Can you show us your hierarchy?

trail gull
wintry quarry
polar acorn
swift crag
#

Your script references leftcurrentBox and rightcurrentBox, so it's presumably attached to some other object.

#

and it's not on the "Destroyer" object, beacuse it's searching for a Destroyer on the thing it hits

trail gull
#

Thats what I thought the issue was but I dont know how to fix it

swift crag
#

If so, I haven't stated a problem yet, so I do not understand.

hollow axle
# tall delta well, this is a class, but not a monobehaviour, so Start() will not work the way...

this is the full scripts:

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

public class BallScript : MonoBehaviour
{
public class Traits
    {
        public float Speed;
        public int[] Color;
        public float[] Scale;

        // Constructor for Traits class
        public Traits(float speed, int[] color, float[] scale)
        {
            Speed = speed;
            Color = color;
            Scale = scale;
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        public Traits balltTraits = new Traits(1.0f, {255,0,0}, {0.5f,0.5f});
        //gameObject.GetComponent<Image>().color = new Color(255,0,0);
    }
}
wintry quarry
slender nymph
trail gull
hollow axle
swift crag
wintry quarry
trail gull
#

When it runs, the two Obstacle(Clone) are created

polar acorn
#

You can't have access modifiers for member variables

#

If that's not underlined in red in your IDE, you need to configure it. !ide

eternal falconBOT
trail gull
polar acorn
honest nacelle
#

!code

eternal falconBOT
polar acorn
#

The reply chain goes cold, I don't know the original question

swift crag
#

I can't do anything with this information.

trail gull
# polar acorn What exactly is the issue with this

When it runs, two gameobjects are created currentboxLeft and currentboxRight
I also have a 3d object called 'Destroyer' with a script called 'Destroyer' attached to it
I want my two gameobjects currentboxLeft and currentboxRight to be destroyed when they collide with my Destroyer gameobject

#

The two Obstacle(Clone)'s are the currentboxLeft and the currentboxRight

honest nacelle
#

Hey, whenever I try to run my code, I'm getting this error :

Assets\Scripts\PlayerController.cs(28,21): error CS0103: The name 'movementVector' does not exist in the current context

swift crag
#

Show your !code .

eternal falconBOT
trail gull
honest nacelle
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
    private Rigidbody rb;
    private float movementX;
    private float movementY;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void OnMove(InputValue movementValue)
    {
        Vector2 movementVector = movementValue.Get<Vector2>();

        movementX = movementVector.x;
        movementY = movementVector.y;
    }

    void FixedUpdate()
    {
        Vector3 movement = new Vector3(movementX, 0.0f, movementY);
        rb.AddForce(movementVector);
    }
}
#

Here is my code

swift crag
polar acorn
trail gull
honest nacelle
#

here's a screenshot of it

swift crag
swift crag
honest nacelle
swift crag
#

Let's thread this.

polar acorn
swift crag
#

Collisions

swift crag
#

It doesn't exist outside of that method.

#

If you want to remember the movement vector so that you can use it later, you'll need to change that.

honest nacelle
#

Oh ok I understand

swift crag
#

Instead of declaring a local variable named movementVector inside of OnMove, you would add a field to the class

#

and assign to that field

honest nacelle
#

I see what you mean, yet it seems to work for the one making the tutorial somehow???

#

Maybe I missed something

swift crag
#

Most likely, yes.

#

They might have added the field after writing the FixedUpdate method.

honest nacelle
#

I'm going to check back the video, I'll be right back

#

Ok it seems I'm quite stupid

#

Basically it's supposed to be rb.AddForce(movement); and not rb.AddForce(movementVector);

swift crag
#

Ah, of course!

honest nacelle
#

My bad and thanks a lot for pointing that out!

swift crag
#

I didn't notice that either :p

#

similarly-named variables can get mixed up really easily

honest nacelle
#

indeed it is

#

especially late at night x)

last grove
#

how do I make this gizmo cube the same size as my object?

swift crag
#

If you set the Gizmos.matrix property to be the matrix of the object's transform, it'll move, rotate, and scale in the same way as the object

#

transform.localToWorldMatrix would be what you want

last grove
#
    {
        Gizmos.matrix = transform.localToWorldMatrix;
        Gizmos.color = Color.blue;
        Gizmos.DrawWireCube(Vector3.zero, Vector3.one);
    }``` This is what I have
swift crag
#

Is that a ProBuilder mesh?

last grove
#

yes

swift crag
#

note how the transform's scale stays at [1,1,1] as you adjust the probuilder object's size

last grove
#

thats what is being used in the tutorial I'm following

swift crag
#

You will need to get the size from ProBuilder component, I guess

#
                var mat = transform.localToWorldMatrix;
                Vector3 size = new Vector3(1, 2, 3);
                mat *= Matrix4x4.Scale(Vector3.right);

I ~think~ this would be correct

#

replace line 2 with something that actually gets you the size, of course

#

I have never touched ProBuilder components from code, so I wouldn't know what to do here.

harsh vault
#

How would I detect when a color changes and to play a sound when its detected?

swift crag
#

Not enough information.

#

Where is this color coming from?

#

Explain what your game is doing.

swift crag
#

why do you need to draw a gizmo?

harsh vault
swift crag
last grove
harsh vault
swift crag
#

I think you want to use the value that's controlling the color.

#
float time = 0.3f;
background.color = Color.Lerp(Color.white, Color.black, time);
#

I presume your code is a bit like this

harsh vault
#

yeah

swift crag
#

look at time, not at the color

harsh vault
swift crag
#

close enough

#

use the value of Mathf.PingPong(Time.time * speed, 1.0f) to decide what music to play

#

I would store that in a local variable

#

then use that to:

  • calculate a color
  • pick a song
#

There's no reason to try to figure out what music to play based on what color you got

toxic wasp
#

hi im very new to unity and the discord (so direct me if this is the wrong channel please).
when i try install unity the 'editor application' fails saying "validation failed". i have run as admin, turned off my antivirus, reinstalled unity hub. any other suggestions would be incredibly useful!

swift crag
#

Have you restarted your machine at least once?

toxic wasp
#

yes i had to do that to turn off my anti virus unfortunately

#

i have vscode installed prior do you think that would be an issue?

swift crag
#

no, that is irrelevant

#

If you're having persistent problems, check the log files. Scroll to the end and look for anything that looks like an error.

#

I think it's... !install ?

eternal falconBOT
#
When Unity fails to install checklist
  • Make sure you have enough space including on C: drive.
  • Check that it's not being blocked by antivirus/security programs.
  • Look through the logs for a real reason why the setup fails they are pinned [here](#💻┃unity-talk message).

If you still have issues, perform a clean install in another location:

  • Install the Hub and Unity in a non-system drive or a clean new folder in the root of C: drive.
  • Failing that use the recovery Refresh option or reinstall OS entirely then repeat the previous step.
swift crag
#

yep

#

note that you should ~not~ need to run this thing as an administrator

toxic wasp
#

will do

silk island
#

Hey so I'm new to Unity and am trying to spawn meteors on a random x axis but whenever I try and run the game with the script in it gives me this error. Is there a specific reason why? Any help would be greatly appreciated

slender nymph
#

remember that it is case sensitive

north kiln
#

use nameof to avoid easy mistakes like these, nameof(Spawn) will evaluate to "Spawn"

silk island
silk island
silk island
queen adder
#

just realized all my SO's are always marked as Serializable, will removing it potentially do any harm?

solemn bobcat
eternal needle
static cedar
#

Monobehaviour also don't need the attribute.

#

And if I remember correctly, you can't have either as a serialized field other than an object field because Monobehaviour and SerializedObject don't have serializable attribute. So you can't make it like any serializable structs or non unity objects.
Normally you can't do that with unity objects but I think I remember forcing it through custom editor and got errors.

lunar root
#

Hi, can somebody help me with making a 2d lever change scenes?

teal viper
buoyant prawn
#

So I’m extremely new to coding, and my goal is to make my player object move around in key inputs by the end of the week, how do I do that, I know it needs to be like

if something about keypressed down

Then transform x,y,z

But I don’t know the specifics, can anyone explain?

keen dew
#

Literally any beginner tutorial shows how to do that

buoyant prawn
#

I tried following one in the unity website and it didn’t work, but also I’m more interested in learning how it works as opposed to what to type, so I can apply that info later

keen dew
#

Show your code and explain the issue and someone can tell what the problem is

buoyant prawn
#

Ok will do once I get back to my pc, thanks

#

this is what I have and its for outputting a textline to the debug log on w press

#

i believe i need to define GetKeyDown(KeyCode.W and Debug.Log globally but i genuinely dont know how

eternal needle
#

also !code for formatting

eternal falconBOT
buoyant prawn
buoyant prawn
gaunt ice
#

do it now, dont do it in future

eternal needle
#

do you have errors in your console?

#

actually nvm i read the code more carefully

#

you have 2 classes there, you dont need KeyCodeExample

buoyant prawn
#

gotcha

static bay
eternal needle
#

If you assign move to a game object, there is no KeyCodeExample created. KeyCodeExample is not created or initialized in move. (you also shouldnt really do this with classes inheriting from monobehaviour)
KeyCodeExample should be in its own file

#

if you want 2 classes that is

buoyant prawn
#
// using System.Collections;
using System.Collections.Generic;
using UnityEngine;

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

    public class KeyCodeExample : MonoBehaviour
    {
        
    void Update()
    {
        
            if (Input.GetKeyDown(KeyCode.W))
        
        {
            Debug.Log("W was pressed");
        }
        
    }
}
}
#

is this correct?

gaunt ice
#

is ``` (the char on top of Tab)

static bay
buoyant prawn
#

i was missing one sorry

static bay
buoyant prawn
static bay
#

ah kk

buoyant prawn
#

wooo its workin! i also realized I had 2 too many curly brackets, thanks yall

static bay
#

No problem, but please make sure to understand WHY it worked.

buoyant prawn
silver dock
#

There's an age option in the game, and i want the character to randomly die between the ages of 80-100. but currently its always dying at 80 doesnt go further. Whats the issue?

fierce shuttle
silver dock
#

yep that was the issue

#

fixed it

#

lmao im so dumb

silver dock
buoyant prawn
#

ok so I have been working on my code for a bit and, it works how I want it too now, aside from tunneling instead of collision occurring at high speeds, the sphere has this script attached and both the sphere and wall have a rigidbody on them, any advice on how to fix the tunneling? I think the solution is to jsut make movement slower, as my project dosent need particularly fast movement, but if there is a way to completely just stop the tunneling, I would like to know, for future issues

#

i apologe for asking so many thingems here

languid spire
eternal falconBOT
buoyant prawn
timber tide
#

Not sure what you mean by tunneling, but using update with rigidbodies is usually a sign of doing something wrong

rich bluff
buoyant prawn
buoyant prawn
timber tide
buoyant prawn
#

what does fixed do as opposed to regular update?

languid spire
rich bluff
#

@buoyant prawn

  1. Update and FixedUpdate run at different tickrates, FixedUpdate is separate loop tied to physics "steps" which can happen multiple time per Update or none at all, depending on settings
  2. Use Update to store input into booleans, use that input in FixedUpdate
  3. To stop tunneling
    3.a - dont disrupt physics steps by moving objects with transform, use forces instead
    3.b - change rigidbody collision detection mode to continous
  4. For it to be smooth, enable interpolation on rigidbody, it means the transform will be smoothly adjusting to actual physical position between physics steps
  5. Do not directly parent the camera to the physically controlled object
buoyant prawn
buoyant prawn
rich bluff
#

GetKeyDown

chilly jetty
#

Hi so i have an issue in my game so for context, my game is a multiplayer fps game, and the issue is about the button. You see if someone creates a room affter a few seconds a button is instatiated and if you click the button you join the room. But my problem is the button/buttons have a text for the roomname but it is too far to the left side the button, and when the button is instatiated it is parented to a gameobject so i tried moving the parent object, but when i pressed ctrl + s to save it reset the position please help

buoyant prawn
#

gotcha

rich bluff
#

Down/Up/ and GetKey is "being held"

timber tide
#

You can cap the amount of force too if that's what you're looking for

buoyant prawn
rich bluff
#

when adding force you can select which force mode to use

#

read which each of them does

timber tide
#
    private void FixedUpdate()
    {
        //cache this eventually
        var sqrMaxVelocity = MaxVelocity * MaxVelocity;

        var v = RigidBody.velocity;
        // Clamp the velocity, if necessary
        // Use sqrMagnitude instead of magnitude for performance reasons.
        if (v.sqrMagnitude > sqrMaxVelocity)
        { // Equivalent to: rigidbody.velocity.magnitude > maxVelocity, but faster.
          // Vector3.normalized returns this vector with a magnitude 
          // of 1. This ensures that we're not messing with the 
          // direction of the vector, only its magnitude.
            RigidBody.velocity = v.normalized * MaxVelocity;
        }
    }

Some project I was working on. Probably not 100% correct as I probably snipped it from stackoverflow/unity forums ;)

rich bluff
#

take into account that this directly modifies velocity, any bumps that would physically change the trajectory will be overriden

timber tide
#

I don't use rb that much; I just needed to prevent some objects randomly being flung into the skybox

buoyant prawn
#

thank you both!

#

is there a better way to move things that I should look into than rb? these little wiki pages for terms are extremely helpfull

solemn fractal
#

hey guys. I am using that code to move a lot of things and it works fine. But now I added it to a new object and it is not working. ANy ideas why would be? ```cs
private void BossMovement() {

    float dist = Vector3.Distance(_player.transform.position, transform.position);

    Vector3 MoveDirection = _player.transform.position - transform.position;
    MoveDirection.Normalize();

    _rb.velocity = MoveDirection * _speed;

}```
rich bluff
gaunt ice
#

what is the value of speed?

rich bluff
#

the alternative to that is to use third party physics system, which is probably over your head

solemn fractal
buoyant prawn
teal viper
gaunt ice
#

have you log Why the superXXX and regular event are triggered at same time

silver dock
# teal viper You'll need to provide some better explanation.

Well okay
events are basically just set the panel gameobject to active

i have two types of events, regular ones which need to keep happening, and supernatural ones from which one needs to be randomly selected and occur only once in a character's lifetime. That all works as expected i guess but the problem is sometimes both the regular and supernatural events happen at once, meaning two panels enabled at once, which makes the game unplayable until you restart

gaunt ice
#
supernaturalEventOccurredThisYear = false; 
if (currentYear != previousRegularEventYear && !supernaturalEventOccurredThisYear){
  TriggerRegularEvent(currentYear);
  previousRegularEventYear = currentYear;
}
if (currentYear != previousSupernaturalEventYear){
  TriggerSupernaturalEvent(currentYear);
  previousSupernaturalEventYear = currentYear;
}
```you have set the supernaturalEventOccurredThisYear =false
#

so your code can be simplified as

if (currentYear != previousRegularEventYear){
  TriggerRegularEvent(currentYear);
  previousRegularEventYear = currentYear;
}
gaunt ice
#

and the two boolean guards:

if (!eventOccurredThisYear && !supernaturalEventOccurredThisYear)//in regualr
if (!supernaturalEventOccurredInLifetime && !supernaturalEventOccurredThisYear)//in supernatural
```can also be simplified as
```cs
if (!eventOccurredThisYear)
if (!supernaturalEventOccurredInLifetime)
```so, no any guard to block the supernatural event happening after regular event happened
#

and there is a simple way to solve this, swap the two triggerXXX in update

silver dock
gaunt ice
#

the boolean guard is "supernaturalEventOccurredThisYear" variable and the only method set it to true is triggerSuperNXXXX so you can just swap the two triggerXXXEvent method

silver dock
gaunt ice
#

yes, let it executes earlier

silver dock
gaunt ice
#

oh i mean swapping the two if blocks, not just the method calls, forgot to say that

#

the check of supernaturalEventOccurredThisYear should be done after TriggerSupernaturalEvent

rich bluff
#

debugger is not scary, its easy to use

silver dock
teal viper
#

Check the Debugging section in the pinned messages.

reef patio
#

Hello, I am having trouble moving my character, this is the error,

hexed terrace
#

!code - show your code

eternal falconBOT
hexed terrace
#

Line 62 is probably trying to access a child transform, and there aren't any

reef patio
hexed terrace
#

Vector3 endPosition = waypoint.transform.GetChild(0).transform.position;

There is no child

reef patio
#

how do I add a child?

eager elm
#

by dragging a gameobject onto another gameobject

reef patio
#

ok whats that suppose to be regarding this 2D Fantasy Character pack?

#

I should rename it to Player.

teal viper
reef patio
#

I need to know how to create a player with the use of a asset given character model, from the asset store.

#

in 2D mode.

#

Any links or suggestions?

frosty hound
#

Maybe look up a tutorial on how to use sprites

reef patio
#

I did those. But this is some other script type that has shooting a magic spell it's suppose to be.

#

Do I have to purchase this guys pack is why?

#

It's a demo

frosty hound
#

Nobody knows what you're looking at so not sure how anyone can actually answer that.

#

If there's a sample scene in the asset, run it and see how it works?

reef patio
#

That one.

#

There is a sample scene.

frosty hound
#

Run the sample scene.unity and explore how they made it work.

reef patio
#

I found in the scene underneath the mage role object has a shadow I added to the scene.

#

The scene in Unity 2D Asset, is only showing a film to be played.

frosty hound
#

There is no video files listed in the package contents ...

reef patio
#

It's known as "scene"

frosty hound
#

A scene isn't a film

reef patio
#

if you play "scene" it opens a game that is just a film.

frosty hound
#

No, it's not

#

It's a scene, that when you run it runs the scene. The point is to look at the objects in the scene and see how they set up their animate.cs component.

reef patio
#

I did check around it, I will check the animate again.

frosty hound
#

Good luck 👋

reef patio
#

It's animate script is some type of auto-script.

#

That goes to the waypoints.

wise fractal
#

can someone help why it isnt showing the text like in inspector I cant drag the text under button

#

[System.Serializable] public class ButtonData { public Button button; public Text buttonText; public string normalText = "CHANGE"; public string ownedText = "OWNED"; public int cost = 0; public bool isOwned = false; }

hexed terrace
#

explain better

ivory bobcat
#

What does it show instead?

wise fractal
#

like in inspector I cant drag Text UI to the desired field I want

hexed terrace
#

Are you using TMP?

wise fractal
#

Yes

hexed terrace
#

public TMP_Text buttonText;

wise fractal
#

thank you!

hexed terrace
#

Text is the legacy text component

oak epoch
#

Just a sanity check: isn't Vector3.Normalize() equivalent to Vector3 = Vector3 / Vector3.magnitude?

ivory bobcat
#

Yes

In other words, to normalize a vector, simply divide each component by its magnitude.

oak epoch
#

Okay so I do have a big bug somewhere and it's not just me mis-remembering the doc. Thanks.

quaint thicket
#

I tried to add a Tag to a GameObject but since it wasn't predefined in Unity it didn't work. Can I use C# to predefine tag types?

wintry quarry
wintry quarry
eager elm
# quaint thicket I tried to add a Tag to a GameObject but since it wasn't predefined in Unity it ...

I recommend not using the Unity Tag system, instead write your own scripts and add them to the gameObjects.

I.e. you add an 'Enemy' script to a gameObject. To see if the GO the player hits is an Enemy you use:

if (TryGetComponent(out Enemy enemyScript))
{}```
You can also make an interface:
```cs
public interface IHitable{}```
and have your Enemy script inherit from it:
```cs
public class Enemy : MonoBehaviour, IHitable```
Then you can look for a IHitable component. That allows you to group tags together and makes it easy to retrieve the correct component.
oak epoch
# wintry quarry Only if the magnitude is greater than 0

Yeah, that was the bug.
Was doing a bunch of distance check between objects and forget to filter for self-check, which result in a null distance.
.Normalize could handle it but /.magnitude was creating non-sense values that created aberrant results further down the code.

quaint thicket
#

Will try

tiny terrace
#

Hello, I want my game to save it's state when the application is paused and this is how I implemented it, Is this correct?

distant mesa
#

Is using SimpleJSON included in 2019 but not 2020?

burnt vapor
#

Why would a Python library be included in Unity?

#

You can download Newtonsoft as a Unity library and use that for serializing/deserializing JSON

distant mesa
#

A project i just got from a collegue has that in the "using" area, and has JSON.Parse, but im using a different unity version and all, so i was wondering if its bc of that

burnt vapor
#

Oh, there are a ton of SimpleJSON libraries, not just Python

#

Well I never heard of it but as I said, you can very easily migrate to Newtonsoft either way

distant mesa
#

I just need an altrernative for the JSON.Parse since it doesnt exist in my own project

burnt vapor
#

Newtonsoft 💯

#

Json.NET is a great library and there's no reason to use anything else

distant mesa
#

ohh okay great

#

ty

tiny terrace
frozen dagger
#

why i cant use SetActive on multiple objects? (private GameObject[] hideObjects;)

gaunt ice
#

it is an array of gameobject

burnt vapor
distant mesa
tiny terrace
frozen dagger
#

weird, gonna take more time cuz i need to hide whole UI

#

and not full canvas

burnt vapor
#

Newtonsoft JSON

distant mesa
#

ohhhhh is it in NuGet

tiny terrace
frozen dagger
distant mesa
#

it wont install them 😔

delicate portal
#

How can I handle going up on slopes with SphereCast?

frozen dagger
distant mesa
#

why

wintry quarry
frozen dagger
distant mesa
#

oop yeah

#

youll get there :P

honest nacelle
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;

public class PlayerController : MonoBehaviour
{
    public float speed = 0;
    public TextMeshProUGUI countText;
    public GameObject winTextObject;

    public TextMeshProUGUI speedText;

    private Rigidbody rb;
    private int count;
    private float movementX;
    private float movementY;
    public AudioClip triggerSound;
    private AudioSource audioSource;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        count = 0;

        SetCountText();
        winTextObject.SetActive(false);
        audioSource = GetComponent<AudioSource>();
    }

    void OnMove(InputValue movementValue)
    {
        Vector2 movementVector = movementValue.Get<Vector2>();

        movementX = movementVector.x;
        movementY = movementVector.y;
    }

    void SetCountText()
    {
        countText.text = "Count : " + count.ToString();
        if(count >=12)
        {
            winTextObject.SetActive(true);
        }
    }

    void Update()
    {
        float speed = rb.velocity.magnitude;
        speedText.text = "Vitesse : " + speed.ToString("F2") + "m/s)";
    }
    void FixedUpdate()
    {
        Vector3 movement = new Vector3(movementX, 0.0f, movementY);
        rb.AddForce(movement * speed);
    }

    private void OnTriggerEnter (Collider other)
    {
        if(other.gameObject.CompareTag("PickUp"))
        {
            other.gameObject.SetActive(false);
            count = count + 1;
            PlayTriggerSound();
            other.gameObject.SetActive(false);

            SetCountText();
        }
    
    void PlayTriggerSound()
    {
        if (triggerSound!= null && audioSource != null)
        {
            audioSource.Stop();
            
            audioSource.PlayOneShot(triggerSound);
        }
    }

    }

}
#

Hey, I have an issue with sound today. Basically, I wanted to pop a sound whenever an object was collected by the player, but I can't seem to make it work. Here's the code :

hexed terrace
#

!code for the correct way to post lots of code

eternal falconBOT
hexed terrace
#

And you're probably not getting past the if condition in PlayTriggerSound()

#

or the if condition in OnTriggerEnter()

#

You need to debug it to see where the code execution reaches

slender cargo
#

is there a bug within unity currently? Everytime I create a script it says "no monobehaviour scripts in the file unity" so I have to rename the script, then rename it back to what it was so that it registers???

wintry quarry
#

from your IDE? From Unity?

slender cargo
#

then opening them in microsoft visual studio

#

then when I save it

#

and go back into unity

#

it says no monobehavour like it hasn't synced

wintry quarry
#

Are you changing the name from VS?

verbal dome
#

This stuff (custom movement) can be a bit complex though. You need some tweaking and its important to visualize what is happening

hearty valley
#

Anyone know a video that teaches you how to make a first person player controller similar to games like phasmophobia, lethal Comapany, and escape the Backrooms ?

#

They all have a rather similar player controller

frosty flicker
verbal dome
#

What makes those games control different? I never played any of them

frosty flicker
#

like when u look down in phas your whole body moves and the cam is actually in the eyes and doesnt just rotate down

frosty flicker
delicate portal
hearty valley
verbal dome
#

One important thing to know about SphereCast is that the hit.distance is not the same as the distance from the origin to hit.point.
It is the distance that the sphere moved

slender cargo
hexed terrace
#

That's not a solution to the overall problem, just a quicker way to get the script working

swift crag
#

I have had some ~weird~ problems when changing the case of a file name, because macOS's file system is case-insensitive

hexed terrace
#

MacOS has VS 🤔

swift crag
#

it has "visual studio"

hexed terrace
#

Yes

swift crag
#

case-insensitive filesystems my extemely unbeloved

swift crag
slender cargo
#

Was happening in college too... so might just be this project weirdly

#

either way, project deadline is tomorrow so oh well

swift crag
#

I have occasionally had Unity miss a file change. Deliberately reimporting the file helped in that case.

verbal dome
#

In what context? If you are dealing with individual angles, the correct method would be SmoothDampAngle

swift crag
#

If you're trying to smoothly rotate towards a Quaternion, then that would be inappropriate

rare basin
#
var leftStick = inputSystem.gameInput.Gameplay.MoveCursorMap.ReadValue<Vector2>();

Vector2 anchoredPosition = cursorTransform.anchoredPosition;

anchoredPosition.x += leftStick.x * cursorSpeed * Time.deltaTime;
anchoredPosition.y += leftStick.y * cursorSpeed * Time.deltaTime;

cursorTransform.anchoredPosition = anchoredPosition;

I am moving my crosshair on gamepad using the left stick. Now, how do I detect if I am over an button (UI) element with that crosshair (cursorTransform)?

eager elm
#

you could fire a raycast from that position

#

cursorTransform.anchoredPosition += (Vector3)(leftStick * cursorSpeed * Time.deltaTime)

is the same as what you wrote, but shorter

rare basin
#

raycast only works with colliders afaik

#

UI elements doesn't have colliders

mystic oxide
#

is it correct using it this way? or just put it on void start

rare basin
mystic oxide
#

i don't find that much resource for addlistener meaning, can you explain what it is?

swift crag
#

You use AddListener to say "when this event happens, tell me about it"

#

It doesn't makes sense to add a listener every time the login button is clicked

opal fossil
#

should I prevent monbehaviour functinality if the monobehaviour is disabled? for example,

public class Damageable : MonoBehaviour
{
  [field: SerializeField]
  public int Health {get; private set;} = 100;
  public void Damage(int damage)
  {
    if(!enabled) return;
    Health -= damage
  }
}
rare basin
swift crag
#

If I tell something to take damage, it'd better take damage

#

But I can't come up with a concrete reason beyond that.

hexed terrace
#

Should be writing your code in such a way that this method can't be called when it's disabled.

EG: Damage wouldn't get called on this because the collider is also disabled so there would be no physics events to start the flow off

swift crag
#

Yeah.

mystic oxide
#

god I just realized how it's work, have to read it again a few time, it isn't that complicated actually

quiet dune
#

Hey, can anyone share some insight into what affects a Physics.OverlapXNonAlloc performance, regarding the size of the space, total objects in the space, objects of given layer in the space, anything else?

honest trellis
#

What is better for spaceship shooting mechanics, raycast or physics based shooting?

sullen wraith
#

Hello. Am i doing something wrong when calling this method? LaserSource Script calls the Laser script method.

gaunt ice
#

GetComponent can return null

polar acorn
sullen wraith
#

Yes sir it does have a LineRenderer 🙂 @polar acorn It broke after i refactored the code a bit

gaunt ice
#

assign the line renderer directly if possible

polar acorn
#

So it hasn't run yet

#

Make the field public and drag in the reference

sullen wraith
#

This works so the lineRenderer seems fine @polar acorn

sullen wraith
polar acorn
wintry quarry
sullen wraith
polar acorn
#

by assigning it in the inspector

sullen wraith
polar acorn
#

you should only use those in situations where a direct reference can't be done

swift crag
#

Indeed. Use it when:

  • there is no way to assign the reference ahead of time
  • the reference is so unambiguous and obvious that it'd be a waste of time to assign it
#

(your threshold for the latter should be very high)

#

I mostly do that when I have a component that must be parented to something, like an entity

solemn fractal
#

Hey guys, if I have an object called boss, and I have a child empty object with only a collider 2d set as isTrigger to ON. I also have in the child a tag. I am using that tag to check for collisions but it is not working. Why?

summer stump
solemn fractal
#

yes

#

the boss yes

#

but the child no

polar acorn
summer stump
solemn fractal
slender cargo
#

What on earth does this mean?

#

I have UnityEngine.UI declared

polar acorn
polar acorn
slender cargo
solemn fractal
polar acorn
solemn fractal
#

its the enemy that contain the ontrigger method

spare umbra
#

When I open my script, intellisense is not working and the expolorer tab is empty

polar acorn
# solemn fractal

Okay, so, neither of these objects have the tag "AreaOfTouch" so the code is doing as it's expected to do

#

and not logging

eternal falconBOT
spare umbra
#

It was working before but suddenly it just broke

polar acorn
# spare umbra

VSCode has a tendency to just die randomly. Hit the regenerate project files button

solemn fractal
polar acorn
polar acorn
solemn fractal
polar acorn
eternal falconBOT
polar acorn
#

You say VSC but both screenshots show VS

swift crag
#

and that script editor has (internal) at the end

#

that implies that you don't actually have the "Visual Studio Editor" package installed

#

alternatively, it implies you have a compiler error that's preventing it from activating

spare umbra
#

lol

swift crag
#

Are you on the "External Tools" tab?

#

It is in there.

hexed terrace
#

!vs

eternal falconBOT
#
Visual Studio guide

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

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

spare umbra
#

I thought you mean vscode

polar acorn
spare umbra
swift crag
#

You have not set things up correctly.

#

!ide

eternal falconBOT
swift crag
#

you shouldn't see "(internal)".

#

Do you currently have any compile errors?

spare umbra
swift crag
#

Do not skip any steps.

swift crag
#

just feels like you're asking for OneDrive to do something that confuses Git

spare umbra
#

I always forget it

swift crag
#

This is not correct

summer stump
swift crag
spare umbra
#

it's completely fine now

swift crag
#

You should follow the instructions. That is a legacy package that doesn't work as well.

#

You should also follow the instructions.

#

The package is installed in the Unity editor.

#

!ide

eternal falconBOT
summer stump
#

It lost support on august 6th
Now both use the Visual Studio Editor package

swift crag
spare umbra
#

Oh

#

Alright

swift crag
#

Both of you should not be trying to "DIY" this. Just follow the instructions.

#

you'll just give yourself a headache otherwise

summer stump
# swift crag it's been deprecated for a looong time

I meant that specific one. Microsoft finally made their own extension on august 6th (I think. It was august at least) and that was the final nail in the coffin of that package. It worked mostly up until then

spare umbra
#

Thanks

swift crag
#

The new package gets rid of some weird restrictions that made Code's analysis slower

gilded sinew
#

i am noob. how do i change color of text

#

its a basic text mesh pro text but i dont see color option

rich adder
gilded sinew
rich adder
gilded sinew
#

no in editor i mean

#

shouldnt there be option to change color of text

rich adder
#

ur in a code channel

#

anyway the Red thing is the color

gilded sinew
#

ah i am dumb wrong chanel

#

but why it doesnt change to red, it stays black now that we started?

rich adder
#

you might have wrong shader somehow

gilded sinew
#

hmm probably

rich adder
#

make a new TMP text object

rich adder
#

see difference

gilded sinew
rich adder
#

you make the base color white

#

then change it where it was red

#

dude this is a code channel

gilded sinew
rich adder
#

so why dont you ask about that

#

the animator has parameters that can trigger different transitions

spiral narwhal
#

Hey so I've got an issue with a ScriptableSingleton, maybe this is not how you use it?

So in Unity, I have this StarterDeckDefinition which is a ScriptableSingleton.
It has a private serialized field, in which I set the values via the use of the Unity inspector (!).
So technically, the field is null, but it's filled by the Unity editor just like any other ScriptableObject.
However, when calling Get() to actually get the starter deck, the field is asserted to null.

This is the line calling the ScriptableSingleton:

        public DeckService()
        {
            Instance ??= this;
            LogInfo("Successfully set the DeckService's singleton instance");

            LogInfo("Now retrieving starter deck definition");
            _deck = new CardPile(StarterDeckDefinition.instance.Get(), true); // <------
            LogInfo("Deck has been set and shuffled");

            LogInfo("Deck consists of these cards:");
            if (debugMode) _deck.Pile.ToList().ForEach(card => Debug.Log($"\t- {card}"));
        }

Is this not how you use it?

open vine
#

Hey, does anyone know how to add functionality to scriptableobjects? I have an inventory that takes an item SO which has name, description, item cost, model. I can assign it to my inventory but I'm not sure how to add unique effects to each item. For example one item would heal health, one would recover mana, add movespeed, etc. but im not sure how to go about this.

spare umbra
#

I tried to reimport the project files but it's not working

wintry quarry
# spare umbra

The message is telling you exactly what's wrong and how to fix it

#

You need only to read it

eternal needle
languid spire
#

Also it not a good idea to keep Unity projects in a OneDrive folder, this can cause problems

spare umbra
spare umbra
open vine
eternal needle
distant slate
#

I created a method that subtracts the percentage of the victim's armor from the damage that was applied to it. Works correctly with any percentage of armor exept 100%. If I give a 100% armor to enemy method output very strange number. Can you say where is the problem? (On screenshot is shown result of this method)

private float CountDamageArmor(float damage) { return damage - damage * Armor * 0.01f; }

open vine
short hazel
swift crag
#

several options here

#

In this case, you're discovering the power of ~floating point imprecision~

#

damage - damage * 100 * 0.01f should just be zero

#

but due to slight errors, it's not exactly zero

#

I would suggest clamping damage to 0 anyway. You wouldn't want 200 armor to make an enemy take negative damage..

#

alternatively, use armor scaling that doesn't need a limit!

#

damage * Mathf.Pow(0.99f, armor) would reduce damage by 1% for every point of armor

#

Any armor formula that involves addition or subtraction will need to be clamped so that it doesn't go into wacky negative values

#

note that this formula causes enormous damage when enemies have negative armor (if that's even a thing you're going to have, of course)

spiral narwhal
swift crag
#

are you supposed to actually create an asset out of a scriptable singleton?

#

i've never done it that way

spiral narwhal
#

Isn't that the point of a scriptable object? But maybe I've approached it wrong, this is the first time I've used it

wintry quarry
#

In a [Test]? [UnityTest]? Also did you create the singleton asset?

spiral narwhal
#
using System.Collections;
using main.service.Turn_System;
using UnityEngine.Localization.Settings;
using UnityEngine.TestTools;

namespace test.EditMode.Turn_System
{
    public class GameTests
    {
        [UnityTest]
        public IEnumerator Sample()
        {
            // Adds the first locale as the selected locale in CI executions 
            LocalizationSettings.SelectedLocale ??= LocalizationSettings.AvailableLocales.Locales[0];

            // Create a new game
            new DeckService();

            yield return null;
        }
    }
}
#

Yes this is the asset

wintry quarry
swift crag
#

But they're really just a way to make a unity object that doesn't have to be in a scene or attached to a game object

#

Also, these are intended for use in the editor only.

#

They're in UnityEditor

#

This is not the appropriate use-case.

#

But I do have just the thing for you...

#
using UnityEngine;

public abstract class SingletonSO<T> : ScriptableObject where T : SingletonSO<T>
{
    private static T _instance;
    public static T Instance 
    {
        get
        {
            if (_instance == null)
            {
                _instance = Resources.Load<T>("SingletonSO" + "/" + typeof(T).Name);
            }

            return _instance;
        }
    }
}

This is how I create "singleton scriptable objects"

spiral narwhal
swift crag
#

but Unity doesn't care about those assets at all

swift crag
#

here are mine

wintry quarry
#

Yeah I think ScriptableSingleton solves this same problem though

#

allegedly

#

at least in the editor

spiral narwhal
#

I'm confused, this is exactly what I want: I just want to define one ScriptableObject which contains the set of cards. This should be a singleton so I can acccess it -> why not use a ScriptableSingleton?

swift crag
#

Because ScriptableSingleton doesn't work the way you think it does.

wintry quarry
#

Well one thing is that ScriptableSingleton is editor-only

swift crag
#

It doesn't look for a single instance of an asset of the appropriate type and give you that

#

That is not what it does.

#

Read the documentation.

#

it exists so that you can remember data between recompiles of your game -- and, if you specify a file path to serialize to, between editor sessions

spiral narwhal
#

Ah okay. Kinda awfully named then imo

#

But thanks I'll do your workaround!

wintry quarry
cerulean bramble
#

I have a question. Does void OnCollisionStay() get called after or before void Update() and if it is before is there any way to make it get called after it or otherwise some way to check for collisions on demand?

swift crag
#

so if it's a FooBar, the SO asset should be named FooBar

swift crag
wintry quarry
#

This shows where it's called relative to update^

#

note it doesn't run every frame, only on frames with physics updates

swift crag
#

I don't believe you can ask for unity to immediately check if you're currently overlapping another collider

#

~but~ you can use the Physics.Overlap* methods to check if there are colliders in an area

wintry quarry
#

and check that list in Update

vague rivet
#

Not sure if this counts as part of the scripting section or whether it is beginner or not, but can I get a little help with something? I tried opening up a project of mine, but it never would. Tried looking at task manager and restarting my whole system. Nothing worked so I eventually deleted Unity Hub and the version of unity I was using. I reinstalled the hub and downloaded the newest version of unity (2022.3.13f1). I am now able to open my project and everything works correctly except the "Starting Selected Interactable" of all my sockets. I know upgrading my engine isn't the best idea, but I found a blog post where someone was having the same issue. I even tested my issue with trying to move things in the editor while the simulation is running, and it seems my problem is exactly like theirs. I can link the blog if needed.

wintry quarry
#

what is "Starting Selected Interactable"?

stable portal
#

this is the bake that u asked i think

vague rivet
#

Part of the XR Socket interactor. Part of basic VR development

rich adder
rich adder
stable portal
#

let me try

rich adder
#

also put pause mode when it disappears, then inspect scene view see where it is

stable portal
#

yet it does

#

if i disable the code it still does

rich adder
#

check the console for eerrrors

#

ur navagent is prob too low from navmesh

cerulean bramble
#

*sorry I haven't replied back to any of the answers I'm just kind of confused about what I'm trying to do right now thanks for helping though

stable portal
#

it gives me this error

#

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

rich adder
#

something you should stil fix

stable portal
#

then there is no other error

rich adder
stable portal
#

yes that might be the issue

#

but i dont know how to fix it

rich adder
#

just notice u have navmesh surface component on enemy/agent

#

thats wrong

#

it goes on the floor

#

then rebake

stable portal
#

OH thanks

#

ill try it

marsh glade
#

Hi, how do I ensure one of my variable properly references a PREFAB through script (as if I dragged it from my folder to an unity window variable) please ?

stable portal
#

thank you the enemy does not fall now thanks

stable portal
#

ill work on it thank you so mutch

polar acorn
rich adder
#

the Unity way

marsh glade
polar acorn
marsh glade
rich adder
#

kinda does

polar acorn
marsh glade
#

It isn't, because it's not possible

polar acorn
rich adder
#

prob a prefab and they want reference obj scene or sum

polar acorn
rich adder
#

true , idk some people dunno what prefab is for lol

grand birch
#

I am trying to create a 2D shmup that incorporates basic math. As you can see from the screenshot, a random number will appear as the "answer" to a simple math problem that the player solves by shooting asteroids with random numbers on them. The problem is trying to make the numbers I shoot transfer to the problem. Right now I am receiving the following error:** NullReferenceException: Object reference not set to an instance of an object
bullet_Script.Start () (at Assets/game_Scripts/bullet_Script.cs:17)
** on this script https://hastebin.com/share/naruhukapa.csharp. Any advice on how to correct this?

summer stump
wintry quarry
wintry quarry
eternal needle
# marsh glade It isn't, because it's not possible

It is, you quite literally just drag it. Now if you are trying to get an object to reference its own prefab, that reference will update to be the instantiated object so you'll need to plug it in another way.

marsh glade
#

I dunno why you assume that dragging it is the solution when I specifically ask for a case where it isn't the solution

wintry quarry
#

make it serialized

#

if you don't want to do that you'll need to assign it in code

marsh glade
wintry quarry
#

ok so

#

copy it from somewhere that is serialized, or use Resources.Load or Addressables

#

those are more or less your only options

marsh glade
#

I ended up using Resources.FindObjectsOfTypeAll then filtering by name

wintry quarry
#

that's quite inefficient

marsh glade
#

it is

wintry quarry
#

why not just use the name directly in Resources.Load

summer stump
wintry quarry
#

or that^

polar acorn
wintry quarry
#

I suspect this is just a case of someone who "hates" the inspector

marsh glade
#

Not quite

polar acorn
marsh glade
wintry quarry
marsh glade
#

I'm just asking for a specific way to do something that isn't dragging it

slender nymph
polar acorn
slender nymph
swift crag
summer stump
swift crag
#

You must explain why instead of just saying you can't

marsh glade
swift crag
#

please read this before wasting our time further

short hazel
#

Alright then keep your secrets

swift crag
#

this is a patently obvious XY problem and it's kind of infuriating to read the chat logs

polar acorn
#

until you've specified why that doesn't work, your problem is solved

grand birch
#

Right. The enemy_generator object spawns the enemy objects at random X coordinates that fall towards the bottom of the screen. The math_generator is part of the UI and will be where the data for the math problem at the bottom of the screen will be stored.

marsh glade
short hazel
#

The way they repeated "it's not possible" made me think of American Psycho, the scene where the guy says

Why isn't it possible?
It's just not.
Why not you stupid bastard

summer stump
swift crag
#

Why can't you just make a serialized field?

#

We might be able to help you if you actually explain the situation to us.

polar acorn
swift crag
#

Perhaps this is something static? I don't know!

marsh glade
swift crag
#

Then I am not helping you.

#

good luck.

polar acorn
marsh glade
#

Yes you aren't

polar acorn
#

You've got a perfectly good one

marsh glade
#

Glad you figured that one out

swift crag
#

nobody else will be interested in helping you either

polar acorn
#

Serialize the field, drag it in

swift crag
#

fix your attitude or leave.

summer stump
marsh glade
polar acorn
short hazel
#

Says the guy angering people by not telling the issue

#

Child beahvior right here

marsh glade
#

Thanks @wintry quarry btw, I tried Resources.Load first but it didn't work, not sure why it worked after renaming my prefab

rich adder
slender nymph
marsh glade
wintry quarry
summer stump
marsh glade
wintry quarry
marsh glade
daring tundra
polar acorn
rich adder
wintry quarry
polar acorn
#

If there's a reason you cannot serialize it, then that could affect other solutions as well

swift crag
# marsh glade My question was (paraphrased) : "Is there a way to reference a prefab without dr...

I am going to give you the benefit of the doubt here.

You are asking about an attempted solution to your problem, rather than your original problem. That is the essence of the XY problem. I linked to an explanation of the XY problem earlier.

The answer to your original problem may differ from the answer to the new problem you invented. Giving people context and explaining what you're trying to do could result in a better outcome.

#

We're not just asking because we like making people type.

marsh glade
polar acorn
#

so rather than trying to solve problems for the goddamn riddler you could say what the situation is so that we can provide the actual solution

slender nymph
swift crag
#

There are some situations in which you, indeed, cannot just drag a reference into a serialized field. Depending on the situation you're in, using Resources may be the best solution.

marsh glade
#

Not sure why they produce different results but they apparently do

swift crag
#

It also might be a problem that you can solve much more effectively in another way. When you refuse to provide context, you are forfeiting those better outcomes (and leaving everyone wildly confused).

wintry quarry
daring tundra
slender nymph
#

no, which is why i gave solutions you can use for specific colliders

distant mesa
#

Hey! I've been having issues with NuGet, i cant install packages anymore, and it gives me this error:
Unable to retreive package list from http://.... System.Net.Webexception: The remote server returned an error: (400) bad request
I tried with different packages and it still doesnt work, tried reimporting the entire project, didnt solve anything, maybe someone here knows a good solution? :) I upgraded my project from 2019 to 2020, could that be the issue? Because it worked just fine before.

swift crag
#

or is this something else

marsh glade
wintry quarry
distant mesa
#

Uhh just the NuGet thing, theres a window for it in Unity when its imported. Just started using it so idk

swift crag
#

I use that pretty often.

#

Can you show the entire error message?

rich adder
distant mesa
rich adder
#

its already in package manager

swift crag
#

there's a unity package for that

#

ye

distant mesa
# swift crag Can you show the entire error message?

Unable to retrieve package list from http://www.nuget.org/api/v2/FindPackagesById()?id='Newtonsoft.Json'&$orderby=Version asc&$filter=Version eq '13.0.3'
System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.HttpWebRequest+<GetResponseFromData>d__240.MoveNext () [0x00152] in <5a2009c85b134970925993880e2ecb2e>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Net.HttpWebRequest.GetResponse () [0x00013] in <5a2009c85b134970925993880e2ecb2e>:0
at NugetForUnity.NugetHelper.RequestUrl (System.String url, System.String userName, System.String password, System.Nullable1[T] timeOut) [0x000b9] in <2dd456e09a61460fa915f49c38c2a123>:0 at NugetForUnity.NugetPackageSource.GetPackagesFromUrl (System.String url, System.String username, System.String password) [0x0006c] in <2dd456e09a61460fa915f49c38c2a123>:0 at NugetForUnity.NugetPackageSource.FindPackagesById (NugetForUnity.NugetPackageIdentifier package) [0x000ee] in <2dd456e09a61460fa915f49c38c2a123>:0 UnityEngine.Debug:LogErrorFormat (string,object[]) NugetForUnity.NugetPackageSource:FindPackagesById (NugetForUnity.NugetPackageIdentifier) NugetForUnity.NugetPackageSource:GetSpecificPackage (NugetForUnity.NugetPackageIdentifier) NugetForUnity.NugetHelper:GetOnlinePackage (NugetForUnity.NugetPackageIdentifier) NugetForUnity.NugetHelper:GetSpecificPackage (NugetForUnity.NugetPackageIdentifier) NugetForUnity.NugetHelper:InstallIdentifier (NugetForUnity.NugetPackageIdentifier,bool) NugetForUnity.NugetWindow:DrawPackage (NugetForUnity.NugetPackage,UnityEngine.GUIStyle,UnityEngine.GUIStyle) NugetForUnity.NugetWindow:DrawPackages (System.Collections.Generic.List1<NugetForUnity.NugetPackage>)
NugetForUnity.NugetWindow:DrawOnline ()
NugetForUnity.NugetWindow:OnGUI ()
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

#

oh its

#

big

#

oops

swift crag
#

Ah, interesting.

#

"NuGet.V2.DeprecatedThe combination of parameters provided to this OData endpoint is no longer supported. Please refer to the following URL for more information about this deprecation: https://aka.ms/nuget/odata-deprecation"

distant mesa
#

Could not find Newtonsoft.Json 13.0.3 or greater.
UnityEngine.Debug:LogErrorFormat (string,object[])
NugetForUnity.NugetHelper:InstallIdentifier (NugetForUnity.NugetPackageIdentifier,bool)
NugetForUnity.NugetWindow:DrawPackage (NugetForUnity.NugetPackage,UnityEngine.GUIStyle,UnityEngine.GUIStyle)
NugetForUnity.NugetWindow:DrawPackages (System.Collections.Generic.List`1<NugetForUnity.NugetPackage>)
NugetForUnity.NugetWindow:DrawOnline ()
NugetForUnity.NugetWindow:OnGUI ()
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

#

also says this

rich adder
swift crag
#

that deprecation happened a few years ago, so that's weird...

#

I would just go ahead and use the unity package.

distant mesa
#

could it be bc i changed unity versions?

grand birch
daring tundra
distant mesa
#

wait i cant do "add package by name"

swift crag
#

ah, you've got an old enough version of unity for that to not exist yet

summer stump
swift crag
#

Is there a reason you're using such an old editor?

distant mesa
#

im using the Mixed reality toolkit,

swift crag
#

Ah, so it needs an older editor. Gotchaj.

distant mesa
#

yup

swift crag
#

The alternative is to just edit your manifest.json file. It's in Packages/.

distant mesa
#

and then put the thing you sent earlier?

swift crag
#
"com.unity.nuget.newtonsoft-json": "3.2.1",

You would add this to the big list of packages. That ought to do it.

lusty horizon
#

Hi all, I'm working on a project and my vs code editor stopped differentiating things like Vector3 and Quarternions. I didn't change my theme or anything, anyone know how I can make it look like the first photo again?

swift crag
#

Sounds like it's not recognizing the .csproj files, and not analyzing your code properly.

#

You should follow the steps here: !ide

eternal falconBOT
swift crag
#

If you aren't using the latest instructions, it might be flaky/randomly decide to no longer work

lusty horizon
#

whenever I open up VS code, it registers like the first image for a split second then goes to the second.

swift crag
#

nice 👍

#

The documentation is pretty good, so make sure you read some of that

distant mesa
#

ohh okay

stable portal
#

hi i have a problem i have the navMesh component and everything is set like the enemy should chase but the enemy just dont move

grand birch
# summer stump Then you are only referencing that ONE off-screen enemy. But you are destroying ...

As I mentioned earlier, the enemy_spawner object I have will generate clones of the enemy object. My goal is to transfer the randomized math_number variable from https://hastebin.com/share/kawocacuse.csharp to the starting_number text variable from https://gdl.space/imayoqavul.cpp and then do the same for the second_number text variable.

distant mesa
summer stump
marsh glade
sullen wraith
#

I have a cube with two child objects. Is it possible to get which way the green arrows rotate by script?

sand glen
swift crag
#

Red - X - right
Green - Y - up
Blue - Z - forward

#

transform.up will be the direction your transform's green arrow points

sullen wraith
#

i have tried to print the position.y and transform.up but both prints the same value

#

thats why i was wondering

swift crag
#

well, position.y is a float

#

and transform.up is a vector3

#

so I would not expect for them to be the same value!

sullen wraith
#

They should be different but they are the same?

stable portal
#

hi i have a problem i have the navMesh component and everything is set like the enemy should chase but the enemy just dont move

swift crag
sullen wraith
swift crag
#

transform.up is giving you (0, -1, 0)

#

Oh, you're talking about the two groups.

distant mesa
#

how would you Parse something with newtonsoft? bc my old code just has JSON.Parse, but that wasnt with newtonsoft.json

swift crag
sullen wraith
#

@swift crag Should the two object not have different orientations?

wintry quarry
swift crag
#

You'll use JsonConverter's methods.

swift crag
#

Kinda feels like you're just accessing the parent object's transform here?

sullen wraith
#

@swift crag

swift crag
#

Okay, that looks fine.

sullen wraith
#

RegisterLaser is in the parrent script