#💻┃code-beginner

1 messages · Page 506 of 1

polar acorn
#

General rule of thumb: Reuse shamelessly as much as you can, but always do a little bit of refactoring every time you touch a script

#

You can ship-of-theseus that brackeys character controller into something halfway decent with enough uses

low wasp
#

Right on, those were my thoughts on it. I just kind of felt like a cheater or imposter.

echo mountain
#

I'd say it's bad not to reuse. Just remember that if "the only tool you have is a hammer, everything looks like a nail". The danger is that you might find yourself using the same solution again and again for many different problems, even if often times better or easier solutions can and should be custom-made.

polar acorn
paper nexus
wintry quarry
# paper nexus

Can you show the inspector of the enemy object?
Can you show your logs when this happens?

slender nymph
wintry quarry
#

Before I loook - my guess is this script was attached to the enemy

paper nexus
#

Yeah, that seemed to be the issue. Thanks Boxfriend.

wintry quarry
#

yep

paper nexus
#

So I know that I needed to remove the script from the enemy, but can I get an explanation of why logically, the enemy was just disappearing? Was it cause the OnTriggerEnter script was being ran by the enemy as well?

slender nymph
#

yes

polar acorn
wintry quarry
#

so if that script is on the enemy, the enemy gets destroyed

#
    void OnTriggerEnter(Collider other)
    {
        Debug.Log("Bullet collided with: " + other.gameObject.name);
        Life life = other.GetComponent<Life>();

        if (life != null)
        {
            life.amount -= damage;

            Debug.Log("Damage dealt: " + damage);
            Debug.Log("Remaining health: " + life.amount);

            if (life.amount <= 0)
            {
                Destroy(other.gameObject);
            }
        }
        Destroy(gameObject);
    }``` See the last line^^
paper nexus
#

Ohhh ok. I'm learning something here.

#

That makes sense. I appreciate it.

wintry quarry
#

code does what you tell it to do 🙏

#

without complaint or argument

#

Instead of directly having the VR hand move the hand rigidbody, create a layer of indirection:

  • VR hardware moves an empty "hand target" object
  • The hand itself with the Rigidbody on it has a script that follows the hand target in FixedUpdate with rb.Move(handTarget.position, handTarget.rotation);
#

that will make the joint behave properly

fervent abyss
#

okay

tribal python
#

Hi, does anyone have any idea why this simple code is returning wrong delta values?

private void Update()
{
        Vector2 mousePos = Mouse.current.position.ReadValue();
        Vector2 mouseDelta = Mouse.current.delta.ReadValue();
        if(mouseDelta.magnitude > 0f)
            Debug.Log($"Mouse pos: {mousePos}, Mouse delta: {mouseDelta}");
}
tribal python
polar acorn
#

https://discussions.unity.com/t/mouse-delta-input/736095/40

Seems like it's related to how the input system handles polling. There's apparently multiple times per frame that the mouse position is "updated" and the delta is only the last one?

Seems like an oversight, but I think it's meant to be used for event based rather than polled in update

tribal python
proven matrix
#

Why is my code not associating with unity? intellisense doesnt work and the public walkspeed var doesnt show up in my inspector?

slender nymph
#

for intellisense, you need to get !vscode configured 👇

eternal falconBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

slender nymph
#

as for the variable not appearing in the inspector, you either have compile errors or you need to save your code and make sure it compiles

proven matrix
#

Ooo okay ty

dim yew
#

where would i change the language version?

#

i can't open the csproj properties for some reason

steep rose
slender nymph
# dim yew where would i change the language version?

just use collection initializer syntax instead of a collection expression.
the only way to change the language version to anything higher than c# 9 is to go through and patch the roslyn compiler which is not supported. and even then you'd only get syntax sugar, you wouldn't be able to use anything that requires a .net version higher than what unity currently supports. it's not worth the effort of doing all that

dim yew
#

also thanks both of you

dim yew
#

thanks 👍

proven matrix
#

How come does my gameobject dissapear when i try to load my game, it also cant be seen in the game scene

slender nymph
#

without any useful info, we could only make random guesses

proven matrix
#

i have this prompy?

#

but nothing to override

slender nymph
#

it's z position is -21 so i imagine it's probably behind the camera

proven matrix
#

Ahahaha

#

silly me

#

it was that

sterile sable
#

Hi i have this gun script that i want when the rotation is more then 90 it will flip the y and its not working

wintry quarry
sterile sable
#

im using the sprite renderer

wintry quarry
#

Using a sprite renderer doesn't have anything to do with what I just said

sterile sable
#

you want to see the code?

wintry quarry
#

That would be a good start, yes.

sterile sable
#

using System;
using UnityEngine;

public class GunScript : MonoBehaviour
{
public Transform bulletSpawnPoint; // Assign in Inspector
public GameObject bulletPrefab; // Assign in Inspector
public float bulletSpeed; // Set bullet speed
public float bulletSpread; // Set bullet spread (optional)
public float fireRate; // Set fire rate (shots per second)
public AudioSource shootSound; // Assign audio source for shooting sound

private SpriteRenderer spriteRenderer;
private float nextFireTime;

void Start()
{
    spriteRenderer = GetComponent<SpriteRenderer>();
    nextFireTime = 0f;
}

void Update()
{
    RotateGun();

    if (Input.GetButton("Fire1") && Time.time >= nextFireTime)
    {
        Shoot();
        nextFireTime = Time.time + 1f / fireRate;
    }
}

void RotateGun()
{
    Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector2 direction = (mousePosition - transform.position).normalized;

    float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));

    if (angle > 90 || angle < -90)
    {
        spriteRenderer.flipY = true;
    }
    else
    {
        spriteRenderer.flipY = false;
    }
}

void Shoot()
{
    // Play shooting sound
    shootSound.Play();

    // Instantiate bullet
    GameObject bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);

    // Calculate bullet direction with spread
    float randomAngle = Random.Range(-bulletSpread, bulletSpread);
    float bulletAngle = transform.rotation.eulerAngles.z + randomAngle;
    Vector3 bulletDirection = Quaternion.Euler(0, 0, bulletAngle) * Vector3.right;


    bullet.GetComponent<Rigidbody2D>().velocity = bulletDirection * bulletSpeed;
}

}

wintry quarry
#

!code

eternal falconBOT
sterile sable
wintry quarry
#

So you want to know what exactly? You said "when the rotation is more than 90"

#

I think you're actually asking if the object is facing left?

sterile sable
#

yes

wintry quarry
#

all you need is this:

float x = direction.x;
if (x > 0) {
  // facing right
}
else {
  // facing left
}```
#

you don't need any of the trigonometry etc

sterile sable
#

ok thanks!

hard mist
#

Hi guys, i have problem and i dont know how to solve it. I am working on a student car racing game with proper RC radio (Futaba T4PM) as an input. I have a functional trasmitter to USB adapter (works fine in VRC PRO - rc racing simulator), but i cannot find a way how to make it work in my project when using the old or the new input system. Any help would be appriciated!

P.S.: I posted this message to input system thread before, but i am absolute beginner so will post it here instead.

bold saffron
#

If I use public enum Enemies {TestEnemy1, TestEnemy2} and I want to use their index number (e.g if TestEnemy1 is selected, and its index is zero), how would I do that?

languid spire
#

cast to int

bold saffron
languid spire
#

do you not know how to cast a variable?

bold saffron
#

tbh idk what that means

languid spire
#
enemyPrefabs[(int)enemyToSpawn];

the (int) is a cast to int

bold saffron
#

oooooh

#

so that's what doing that is called lol

#

thank you very much :)

silk gale
#

how would i call a script whenever i change a tilemap in the editor? like just pretend that i want to Debug,Log("tile map has changed")

river schooner
#

Hi, I'm new to Unity and I'm trying to make a first-person 3D game. For movement, running, jumping and crouching I've used a starter asset and now that I want to add animations to my character I can't find any tutorial on how to do it. I don't know if anyone could help me.

fickle plume
#

@river schooner Don't cross-post please. And not a code question

austere crypt
#

Collider not working, I tried with rigid body but nothing work

short hazel
#

Please post screenshots from your computer. Pictures of screens are hard to read

#

Discord can run in a browser

#

Code should also be posted correctly

#

!code

eternal falconBOT
wintry quarry
austere crypt
wintry quarry
#

you mean running your code like OnCollisionEnter?
Or something else.

austere crypt
#

Yep

wintry quarry
#

OnCollisionEnter requires a dynamic Rigidbody

#

And it requires your object to touch another object

austere crypt
#

I tried that also

wintry quarry
#

show what you tried and what happened

#

because this is a really basic thing, so 99% chance the reason is you just didn't set it up properly.

austere crypt
#

Ok

#

Wait

polar acorn
#

it can't even stand up straight

queen adder
#

hi, im putting together a script that plays a melee attack animation, im using the new input system.

i keep getting this error, but i dont know what to do to fix it

"NullReferenceException: Object reference not set to an instance of an object
PlayerController.OnDisable"

#

here is the code

#

everything else about it is fine, it should be working but i think ive missed something?

austere crypt
queen adder
#

oh? its effecting both lines, 1 error for each of the lines

short hazel
# queen adder here is the code

Attack or Attack.action did not have a value (it was null). Therefore attempting to access anything with the . operator on a null reference throws that exception

wintry quarry
#

remember I mentioned it needs to be dynamic for OnCollisionEnter

wintry quarry
queen adder
austere crypt
wintry quarry
#

you need to UNCHECK it

short hazel
wintry quarry
#

two trigger colliders will work, as long as one of them has a Rigidbody

austere crypt
#

my bad but i tried without kinematic but same problematwhatcost

wintry quarry
#

so far you haven't shown a single valid combination of settings

#

Once you have a valid combination, it will work

austere crypt
wintry quarry
#

FOr OnCollisionEnter you need:

  • One dynamic Rigidbody,
  • Two colliders
  • neither collider trigger
short hazel
wintry quarry
# austere crypt

ok... so now those two objects need to actually collide with each other, while the game is running

#

I'm noticing you put "Floor Collision" script on one of the cubes, that seems odd.

austere crypt
#

with debug log

#

i also tried with .moveposition()

#

i think unity is broken

wintry quarry
#

moving via the Trnsform gizmos in the editor won't wake it up afaik

#

or jsut let the Rigidbody drop onto the other thing

#

rather than moving it via the gizmo

austere crypt
wintry quarry
#

other things to check:

  • The collision matrix in your physics settings
austere crypt
#

all tick

#

i am into this shit past 3 hour

wintry quarry
#

Do you have Time.timeScale set to 0 or something?

#

IDK i've never seen an issue with this

austere crypt
#

checked too many blog and forum pages

austere crypt
#

gonna see

austere crypt
#

thanks guys , bye

#

good night

valid needle
#

hey there, so i'm making a top down shooter as a test project, and everything is working, except the point in which the bullets shoot from, and the bullets constantly firing after i press the input once. the code and inspector are both shown below, aswell as my player prefab, just in case that helps. can anyone help with this?

#

The game object named "GunOffset" is supposed to be the fire point, but it just doesnt shoot from there whatsoever, rather it shoots from its prefab's position

acoustic sequoia
#

Is it possible for someone to inpliment a minimax algorythim for my game if i provide the nodes and their relationships? i need help starting this project up and i need some kind of Ai to help me determin best moves. I have been reading up on the minimax algo, and i can't seem to understand how to apply it to my game board. help please lol idk what to do

steep rose
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

acoustic sequoia
eternal needle
#

And trust me, abandon the idea of using other languages purely for speed

acoustic sequoia
eternal needle
acoustic sequoia
acoustic sequoia
eternal falconBOT
eternal needle
eternal needle
acoustic sequoia
eternal needle
acoustic sequoia
#

i'm just going to leave this server. no one ever gives me good advice no matter how nice i am. this community is not for me.

steep rose
#

what is going on, i suggested something now there is division, im not sure how what bawsi was saying is gaslighting, we gave you advice from above so use it

teal viper
#

If you feel like everyone around you is wrong,maybe that's a clue that something is wrong with you.

queen adder
#

when watching videos i notice that for a lot of people the specific pieces of code that highlight for them, dont highlight for me, i aslo dont get red error lines under mistakes ive made, is there some sort of setting i can change? i use C#

eternal falconBOT
eternal needle
#

Follow those steps and you'll have the same highlighting and error messages

queen adder
#

ah thank you!

polar acorn
steep rose
#

i cant tell if he was a troll or not

ripe shard
#

maybe just annoyed that he couldn’t BS anyone

faint agate
#

Hello,
goal : I want the screen to turn red with full screen pass renderer as the player does a 180. The screen effect(it turning red) percent will be connected as the player turns around so it wont be at 100% unless the player has done a full 180.

I have a full screen pass renderer set up and tested in code, I made the red effect a float I can control in code but how Ill approch this goal. I'm not sure, I know what I want and need to do but Im not good enough at coding to execute and the internet is not helping on this one.

queen adder
steep rose
#

did you regenerate the project files?

queen adder
#

how do you regeneratr project files

zenith cypress
steep rose
#

in unity

queen adder
#

how long does this take?

steep rose
#

shouldnt take to long, well it depends on your project size

queen adder
#

thanks!

pure crest
#

Hey guys, I have an interesting problem, I'm working on a simple mechanic to pick up an object and old it in front of the player and right now I just have it to left click. It's mostly working, except the fact that it doesn't pick up when you just click once, it picks up only when you hold the LMB for like 0.5 seconds. It's a little annoying just because it doesnt feel as snappy and I was wondering if anyone might know why. I'll post the code below

wintry quarry
faint agate
wintry quarry
#

Nor this part && GameObject.FindWithTag("PickUp")

pure crest
pure crest
wintry quarry
#

this code is just seeing if such an object exists in the scene

pure crest
#

Oh! Ok I didn't understand that, thats helpful!

wintry quarry
#

if (hit.collider.CompareTag("Pickup")) < notice how we're actually using the hit object here

pure crest
wintry quarry
#

No I don't think this is related to the wait .5 seconds problem

#

i don't see anything in here that would cause that

#

It's probably in the Interact function itself on the object

faint agate
wintry quarry
#

you should add Debug.Log there and make sure it's being called immediately

pure crest
wintry quarry
#

and compare your player's facing direction with that recorded forward direction

#

it's unclear what would trigger it being recorded initially though

#

or if there's some hardcoded or scene-determined direction that should be

#

or maybe you want something like "if they do a 180 within a certain amount of time" or something

pure crest
wintry quarry
#

This code only handles the initial click and initial interaction

pure crest
wintry quarry
pure crest
#

it doesnt

wintry quarry
#

well what scripts does it have

pure crest
#

Sphere collider

#

and just a basic implementation of interact that isnt being used

wintry quarry
#

well again this code doesn't do anything except on the intiail mouse click

#

so the behavior of holding etc has to be coming from elsewhere

#

unless you've modified the script

faint agate
#

i did look online for awhile before asking

wintry quarry
#

that's going to aim your camera in the direction of startPos.

faint agate
#

how about : startPos = Camera.main.transform.forward;

#

private Vector3 startPos;

wintry quarry
#

yes, that will do the opposite

#

it will save the camera direction in the startPos variable

#

although it's not a position

#

it should probably be called startDirection

faint agate
#

okay thank you

copper orbit
#

what happens if the value in serializefield differs from the one initialized in c# script? it always takes serializefield's value right?

ivory bobcat
copper orbit
#

are you saying that the code takes priority if the object was like a prefab that was instantiated into scene?

ivory bobcat
copper orbit
#

is it? I dont know

ivory bobcat
#

https://docs.unity3d.com/Manual/Prefabs.html

Unity’s Prefab system allows you to create, configure, and store a GameObject complete with all its components, property values, and child GameObjects as a reusable Asset. The Prefab Asset acts as a template from which you can create new Prefab instances in the Scene.
So a component instance would be attached to the game object prefab. And you'd create prefab instances in the scene ect - my interpretation of it.

faint agate
wintry quarry
faint agate
#

var dot = Vector3.Dot(startDirection, _180Direction);
how would I print this so I can see the direction of 1 - 180 live as I turn ?

#

_180Direction = Camera.main.transform.forward * -1;
I did this for the 180 the same way I did start direction, I hope that should be fine

#

I just did * -1 so its behind the cam

drowsy oriole
#

Hi, I need some assistance with this code. It is supposed to disable an object and enable another 2-5 seconds after it is enabled https://hastebin.com/share/urojukuzux.csharp

eager spindle
#

All the code should be kept in the ienumerator rather than the onenable function. The only thing the onenable function should do is call the ienumerator

#

Additionally, you cannot just call Delay() like that, you'll need to use StartCoroutine(Delay())

#

Spoilers: the final code may look something like

||```
void OnEnable() {
StartCoroutine (ToggleItem());
}
public IEnumerator ToggleItem() {
// Toggle Parents here
yield return new WaitForSeconds(3)
// Toggle Parents here
}

near wadi
near wadi
#

interesting.. 2020.1 supposedly had it too (different source).. maybe just a doc reference error. i will see if i can test it in 2022.3, thanks

near wadi
#

Ok, so far, so good. seems to be working in 2022.3. So, seems a doc reference error :/

        [OnOpenAssetAttribute(1)]
        public static bool OnOpenAsset(int instanceID, int line)
        {
            Dialogue dialogue = EditorUtility.InstanceIDToObject(instanceID) as Dialogue;
            if (dialogue != null)
            {
                Debug.Log("OpenDialogue");
            }
            return true;
        }
languid rivet
#

quck question.. what will Vector3.project give?
v1 vector is projected along direction vector d1.
will I get the pink line or the green line. my assumption pink line..(which would mean direction of vector d1 doesn't matter.. just the line matters)

misty breach
#
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Tilemaps;

public class A_1 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        TileBase a_1 = share_data.keep_1_1;

        if (a_1 == "Hill_11"){
            print(a_1);
        }

       
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
#

i dunno how to do this but

#

i wanna print a_1 if the value inside it is Hills_11

night valve
#

Debug.Log(a_1);

misty breach
misty breach
teal viper
languid rivet
night valve
misty breach
night valve
#

So you need a scriptable object name

misty breach
#

Hills_11 (UnityEngine.Tilemaps.Tile)
UnityEngine.MonoBehaviour:print (object)
A_1:Start () (at Assets/pic_dat/scripts/A/A_1.cs:20)

misty breach
night valve
#

Then you'll need to map it the other way, like having tile base as a key to dictionary with scriptable object or string values

misty breach
misty breach
night valve
#

var dict = new Dictionary<TileBase, string>()
Then you access it like an array but instead of integer index use TileBase object. But this is hardly a good solution. Probably it's best to set the .name of TileBase gameobject to the desired string and then access it like tile.name ig

night valve
cunning raven
#

hi is there a way to keep the text characters withing the box field?

#

TextMeshProUGUI

astral falcon
languid spire
cunning raven
cunning raven
languid spire
#

oh, it does

cunning raven
#

ok my bad formulate of question, i'll try again, how do i keep text in the box field and have the autowrap thingy when it gets too long

night valve
#

Over-flow so like text flowing over the rect border

astral falcon
#

you could use the autosize feature

#

or autofit I think its called

#

Or you let the user enter as long as he wants while masking it and when done editing, replace the visual text with some predefined length + "..." or something.

runic lance
#

I think there's a wrapping option with ellipsis builtin with TMPro already

astral falcon
#

Ah, how convenient if so 🙂

runic lance
#

the easiest way would be to fiddle with the settings in the inspector until it's how you want it, then just copy the properties over to the code

cunning raven
#

the ellipisis mode is showing "..."

#

i want it to show the lastest character and hide the first ones, dunno how to explain

astral falcon
#

you want the elipsis to be at the start

drifting geode
#

!code

eternal falconBOT
cunning raven
#
    TextMeshProUGUI textField;
    textField.rectTransform.SetUIParent(inputField.transform);
    textField.rectTransform.AnchorToStretchInParent();
    textField.font = Bundle.FontAssetFor(BundleFont.myriad);
    textField.fontSize = largeFontSize;
    textField.alignment = TextAlignmentOptions.Left;
    textField.color = ThemeColor.neutralTitle;
    textField.overflowMode = TextOverflowModes.Ellipsis;
drifting geode
#

can someone help me with this

languid spire
#

not unless you actually ask a question about it

drifting geode
#

It just always creates new instances instead of incrementing the item amount by 1

languid spire
#

So you need to Debug the conditions in your if statement

runic lance
#

very likely you're adding a different instance of the Item class, even though it has the same properties

drifting geode
languid spire
drifting geode
#

Is it better to comment it out rather than remove it completely and try something new?

runic lance
#

if the Item is something like a MonoBehaviour and it's just laying around the scene, you're probably collecting a different one than the previous

languid spire
#

no, just debug it

languid spire
#
        Debug.Log($"{item.itemName} {inventory.Contains(item)} {item.isStackable} {item.amount} {item.maxAmount}");
drifting geode
#

Oh that's what you mean sorry I'm dumb

languid spire
#

debugging 101. If your code is not doing what you expect. Print the values to the console

drifting geode
#

Oh I got it

#

Instead of inventory.Add() is should've used only Add()

neon ivy
#

is there an easy way to do x amount of raycasts in every direction?

runic lance
neon ivy
night valve
#

I assume the list is part of the MonoBehavior so you'd need to call DontDestroyOnLoad on this object. Or make that list static

night valve
vernal thorn
night valve
#

static List<some type> list;

hexed terrace
#

Making things static just to have them available across scenes isn't a good solution, you need to tidy it up yourself when it needs to go away.

vernal thorn
#

Thanks !

night valve
#

Right, was about to say this. Probably better idea would be singleton pattern or DDOL

hexed terrace
#

For Singleton, it depends on the use of the class - again, you don't want to just make everything a singleton for cross scene

neon ivy
night valve
#

Well yeah, making a singleton only for holding a single list wouldn't be good. But if you actually need such persistent list, most likely it could be placed in some more complex singleton like GameManager or smth. However such manager could be just a regular gameobject with DDOL

neon ivy
#

a sphere cast is just a raycast that uses a sphere instead of a point. if I didn't need a direction I'd use an overlap sphere but I do need a direction

night valve
#

Then probably it would be sufficient to just construct an array of direction vectors and raycast them

#

Or your UV solution

runic lance
#

otherwise you just need to do a bunch of raycasts, no way around it

neon ivy
#

well yea I am trying to do a bunch of raycasts, but I need to equally space them around the player

night valve
#

Right, uv sphere won't give you even distribution. But googling helps. You may consider looking at Fibonacci sphere algorithm

neon ivy
#

I think I'll try to generate an Ico sphere of x amount of vertices

night raptor
# neon ivy I think I'll try to generate an Ico sphere of x amount of vertices

As tyrr mentioned, Fibonacci sphere is often used to solve just this problem. That way you should have much greater freedom to choose any number of rays you want. With ico sphere I believe you can only choose resolutions from the exponents of 4 (triangle count of 20 * 4 ^ resolution if I'm not mistaken) so you are very limited in that regard

rustic maple
ivory bobcat
#

If so, perhaps there's an infinite loop else we'd need to know more information.

#

Also check your console logs in the case that there's an error.

#

At a closer look, it seems as though you've simply paused the game or it has paused for some reason.

white rune
#

https://paste.ofcode.org/sufg3eQEmEGE9LmgLbLrJu
I've been tryina code up a neat lil platformer and it seems like there is a flaw with how I've created the walljump functions with the logic or something, and I cant for the life of me figure out what the problem with it can be

ivory bobcat
wintry quarry
#

You got an error so the game paused because of error pause being turned on.

white rune
ivory bobcat
tulip nimbus
#

Why does this script not change the Scene? Im using UnityEngine.SceneManagement

languid spire
tulip nimbus
#

I do, and with UI Elements like Buttons changing the scene works

languid spire
#

show the build settings

tulip nimbus
languid spire
#

Also, why is there no debugging in your code?

tulip nimbus
#

I originally had Debug.Log codes but i removed them after the rest worked, except for the Scene changing

#

Putting the SceneManager.LoadSceneAsync("Mainmenu") as the first line in the if statement in the first pic it works, but any other position does not

languid spire
#

then, at a guess, you are getting a null ref exception in the code

#

put the debugs back and then show the console

tulip nimbus
#

okay so i figured that everything after the second line in AybarsTap() does not work anymore, it also displays this error message. I put the other code into a comment and after the first two, GameOver(); is never called.

What do i have to do to fix this nullRefrence?

languid spire
tulip nimbus
#

instanceSM is static, do i just give them any value?

languid spire
#

of course not, I presume you are using the singleton pattern which you should know how it works if you are using it, so I'm guessing you have a script execution order problem

#

or you are not setting up the singleton pattern in StatsManagerScript correctly

tulip nimbus
#

I see, its probably null and it could be that i didnt set it up correctly. Im not fully aware of all the functionalities since i wanted a quick way to access variables from diffrent scripts so i have to read myself into that more.

This is how i set up my two static instances: instance and instanceSM

public static StatsManagerScript instanceSM;

private void Awake()

{
instanceSM = this
}

And the same for GameManager and instance without the SM

languid spire
#

odd, missing ; there

tulip nimbus
#

there are ofc lines of code between but this is how i did it

tulip nimbus
languid spire
#

ok, so you need to debug.log that to see if/when it is being executed

tulip nimbus
languid spire
dim yew
#

getting a null reference exception here. i have no idea why because i have no idea what its trying to access

#

could this be related to the raycasting i'm doing?

languid spire
#

So, if nothing is hit then MouseHovering().collider will be null

dim yew
#

ahhh thanks

#

im a bit new to raycasts

languid spire
#

RaycastHit is a struct so cannot be null, collider will only be not null if something is actually hit

dim yew
#

so which is the error coming from?

#

the collider i assume right

languid spire
#

collider.gameObject. if collider is null gameObject cannot be accessed

dim yew
#

ic

#

thanks a ton

neon lynx
#

I have some weird error. I have only yellow errors on the console and when I start playing after a while some specific scripts stop working until I press a key that make the player jump, then the specific scripts work again.
So maybe I should fix the yellow errors on the console? Or I should make a new script to solve this particular error?

slender nymph
#

yellow errors
Those are called warnings, not errors. And you need to be more specific about the issue if you want help solving it

neon lynx
polar acorn
#

You're going to need to say what warnings you're getting, what the code looks like, what you're expecting to happen versus what actually is happening, etc.

languid spire
neon lynx
# languid spire have you actually debugged any of this or are you just making assumptions?

It's what I've noticed while playing, but I have to debug it. But I think It is possible that the ground collision detection is temporarily failing due to issues with Colliders or with the logic that determines when the player is on the ground. It is surely for that reason that the error happens.
Is there a better way to detect collisions than the OnCollision events?

languid spire
neon lynx
#

Yeah, I will do it.

turbid robin
#
    private IEnumerator Spin()
    {
        float spinDuration = 1f;
        float totalRotation = 360f; 
        float elapsed = 0f;

        while (elapsed < spinDuration)
        {
            float angle = (totalRotation / spinDuration) * Time.deltaTime;
            transform.Rotate(0, angle, 0); 
            elapsed += Time.deltaTime; 
            yield return null; 
        }
        
        transform.Rotate(0, totalRotation - (elapsed / spinDuration * totalRotation), 0);
    }```
when this get called i see the "spin" as an animation of a flip of a page. why? it should be a spin around
polar acorn
#

You can select the object in the inspector and change the rotation values to see which axis you actually want

tender breach
#

The problem I had was that either clones or child objects can't be detected via collision. Is there anyway I can make it so that they can?

tender breach
#

That didn't work.

verbal dome
#

I wish the docs pointed this out..

polar acorn
turbid robin
turbid robin
#

because i get the rotation from the bottom left point, i want it to rotate from the center

polar acorn
tender breach
#

That's my code.

#

AND YES I FORMATTED IT

tender breach
turbid robin
polar acorn
# tender breach https://pastecode.io/s/qjnem61f
  1. You really need to learn how to use logical operators like && and ||
  2. Please don't use a paste site that fills my browser with full screen LL Bean advertisements, there are plenty of options in the bot message from !code
  3. Please show the inspectors of both objects involved in the collision that you're not detecting
eternal falconBOT
neon lynx
polar acorn
neon lynx
polar acorn
neon lynx
haughty reef
#

Hey! How could I make a mouse sensivity slider, or atleast 3 buttons for sensivity?

wintry quarry
fallen mirage
#

How can i make a weapon that aims at the mouse?

cosmic quail
fallen mirage
#

I cant find any for unity 6

rich adder
cosmic quail
rich adder
#

yes the API stays the same more or less with a few methods changing names, only be mindful of the js-like syntax ones those aren't valid for c# but the logic is the same

fallen mirage
#

Hm ok Thank you im going to try my best. Freakbob out...

inland perch
#

and then a empty script for EnemyMovement

rich adder
inland perch
rich adder
#

look how the player moves, its not that much different to do on enemy except the input comes already in code

inland perch
#

this is my enemy and i want it to walk like the 6 blocks from the left to the right

inland perch
#

and that he always keep running forward

rich adder
#

You need to push it with .velocity

#

use the horizotnal speed on x axis, keep the rb.velocity.y on y axis
eg
horizontalInput = 1 // goes right , -1 goes left
rb.velocity = new Vector2 (horizontalInput * moveSpeed, rb.velocity.y)

#

later you can add raycast for easy detection of edges

#

make it kinematic if you don't want player to push it

inland perch
#

ooh alright

exotic terrace
#

hey

#

I need help with 3d player movement with animations ill post my code here

rich adder
# exotic terrace hey

dont just randomly post your code and actually make an effort to formulate a question that makes sense with description

eternal falconBOT
rich adder
#

ah and of course you say the same thing 3 times instead of stating what's actually wrong with it

slender nymph
#

read the entire bot message

exotic terrace
#

yes ill ask

#

full questions with the code

slender nymph
#

you can skip the 5 minutes of pointless back and forth by just asking your question.

exotic terrace
#

its not pointless i want you to think im not a newbie or smth acting like this by confirming ill follow the rules

slender nymph
#

then ask your fucking question instead of doing this whole pointless back and forth that enforces the belief that you have no idea what you are doing

exotic terrace
#

no cussing

slender nymph
#

as i said in the first channel you were doing this in, if you refuse to actually read the information presented to you, then you are not going to have a good time getting help

slender nymph
#

yeah i'm not helping you now. good luck

frosty hound
#

@exotic terrace Just ask your question, stop spamming this noise.

exotic terrace
#

he cussing at me for no reason report him

frosty hound
#

If your next post isn't a proper question, you'll be muted.

outer wadi
#

I was just about to ask something but I got it already so nvm

exotic terrace
prime pier
#

hey. ive got some code for moving platforms and i need the player to be able to move without jumping on the platforms. im thinking i need something to check if the player is moving and if they are, dont let the platforms move the player, but if they arent the player should move with the platform. anyone know how i would get to doing that?

polar acorn
frosty hound
#

!mute 397878993686364160 1d You can try again tomorrow. When you return, start with asking your question with the relevant details.

eternal falconBOT
#

dynoSuccess kiryu0122 was muted.

slender nymph
frosty hound
#

You don't need to fuel it @outer wadi, thanks.

polar acorn
prime pier
polar acorn
prime pier
polar acorn
slender nymph
#

in other words they "query" the current state of physics, hence why they are called physics queries

wispy wraith
#

Hi, can anyone tell me how to send code in the proper format?

eternal falconBOT
wispy wraith
#

thank you🙏

fallen mirage
#

Whats wrong with this Code
I want my weapon to follow the mouse:

The weapon rotates towards the mouse only when it is positioned on the right side of the player

void Update()
{
Vector3 mousePos = Input.mousePosition;

 Debug.Log(mousePos.x);
 Debug.Log(mousePos.y);

 //Vector3 MousePosition2 = new Vector3(mousePos.x, mousePos.y, 0 );

 Vector3 rotation = mousePos - transform.position;

 float rotZ = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;

 transform.rotation = Quaternion.Euler(0, 0, rotZ);

}

slender nymph
#
  1. !code 👇
  2. unless this object that is following the mouse is in screen space, then you need to convert your mouse position from screen space to world space using Camera.ScreenToWorldPoint
eternal falconBOT
slender nymph
#

also the atan2 is unnecessary, once your mouse position is correct you can just set the object's transform.up (or transform.right depending on its resting rotation) to the direction (which you've named rotation in your code)

rich adder
#

Input.mousePosition is the pixel coordinate of the mouse. It would not make sense to use that in the 3D world

fallen mirage
#

When I use ScreenToWorldPoint, the weapon follows the camera and not the mouse.

autumn gull
#

im pretty new to C# coding and i have this error and idk whats the issue?
Assets\Scripts\PlayerController.cs(31,34): error CS0029: Cannot implicitly convert type 'UnityEngine.Quaternion' to 'UnityEngine.Vector3'

fallen mirage
#

and my game is 2D

slender nymph
rich adder
slender nymph
slender nymph
#

start by configuring your !IDE

eternal falconBOT
rich adder
#

but do configure your IDE asap , this would underline red

fallen mirage
fallen mirage
autumn gull
slender nymph
rich adder
fallen mirage
#

perspective

rich adder
#

ahh

#

thats a problem in 2D

fallen mirage
#

why

slender nymph
rich adder
#

cause of nearClipPlane

rich adder
fallen mirage
#

I changed it to this, but it still does not work.

slender nymph
slender nymph
rich adder
#

yeah strikes me odd to use Prospective for 2d lol I never used that

#

2D sprites don't need depth

fallen mirage
#

doesnt hollow knight use a perspective camera?

slender nymph
#

define "looks better" because that's subjective but also if you are just using a bunch of flat sprites and don't need depth anyway, then it's also just wrong

rich adder
#

much easier to use plane.raycast then if you really want prospective

#

but yeah for 2D sprites just weird, it makes more sense 2.5d with some meshes
(gta 2)

slender nymph
#

alright. well you've already got your solution on that page i linked earlier so just read it 🤷‍♂️

#

also that's called depth, because it's all 3d still

fallen mirage
#

my code doesnt work...

#

i implemented the code that u sent

slender nymph
#

show what you've tried

#

read the other solutions then

fallen mirage
slender nymph
#

you know there's more than just one thing on that page

slender nymph
fallen mirage
#

yeah should i use screenpointtoray?

#

ok

slender nymph
#

you'll want a plane representing the plane that the object you want to rotate is moving on

fallen mirage
#

i switched to orthopgraphic and changed the code. it works. Thanks for the answers

runic urchin
#

hey, could someone help me figure out whats wrong with this?

wintry quarry
#

you can't write arbitrary code like that outside of a method

#

you can't call randomizer.Next(..) in a field initializer, which is what you're trying to do

#

int funcToChoose is the field

#

int myField = blahblah is a field initializer

#

The error is telling you quite straightforwardly that you can't call a non-static method in a field initializer (.Next(..) is the method in question)

#

You should put this code in Awake, or Start, or OnEnable

runic urchin
#

oh, i see. thank you so much lol, im new to coding so i didnt know what any of it ment lmaoo

neon lynx
#

Ok, in the script, make the platform the parent of the player but only when the player collides with the platform

#

Use the tag Player to check if the player collides with the platform

#

Use empty gameobjects for the positions that the platform have to go

#

Use public Transform PositionA and public Transform PositionB

runic urchin
#

ok, so i have been trying to do different things for the last two hours but i have had no luck with figuring out how i could choose one of these options randomly lol. can anyone help out?

polar acorn
runic urchin
#

alright, lemme try that out

rocky canyon
#

@runic urchin and are u aware u have two MoveLeft functions in ur screen-snip, just curious

runic urchin
#

yeah lol, i just had it there so i would remember which one i wanted a higher chance to happen

polar acorn
rocky canyon
#

oh okay.. just making sure wasnt a typo u missed

runic urchin
#

yeah lol, mb

rocky canyon
#

mediocre coding flex lol

runic urchin
#

i actually tried to use a switch statement earlier but i guess i did it wrong or smth lol

rocky canyon
#

i asked chatgpt too.. it seems to think a list of delegates is a better solution

polar acorn
rocky canyon
#
    void Start()
    {
        // Array of movement functions
        MovementFunction[] movements = new MovementFunction[]
        {
            MoveDown,
            MoveLeft,
            MoveRight,
            MoveUp
        };

        // Choose one function randomly and call it
        int randomIndex = Random.Range(0, movements.Length);
        movements[randomIndex](ref currentTile);
    }``` this is the pasta vomit it created
rocky canyon
#

once u write enough if/else chains u tend to see them as a better alternative

slender nymph
#

they could alternatively not make their methods use a reference parameter and instead return the desired tile and use a switch expression which can do pattern matching if they wanted to support ranges and stuff

rocky canyon
#

but ya, ranges and approximations and stuff still better for if else then i guess

#

Many paths lead to the same destination

#

thats what i adore about game-dev

runic urchin
#

yeah i cant wait till i learn enough to be able to write my own code for stuff lmao, im at that point where im tasking existing code and stringing it with other stuff to get stuff to work. not that using other code is bad ofc lmao

rocky canyon
#

that was my 2nd step..

#

first was wrapping my little brain around coding in general..
then it was robbing and stitching together codebases
and then it was experimenting on my own and creating my own code

#

here lately.. ive written my own editor scripts to replace the need for NaughtyAttributes.. (thats my peak) lol

#

for now 😈

runic urchin
#

yeah i have always wanted to make my own game and id always start but give up. now im really trying to work on this one project till the end, that way i can prove to myself that i can actually do this lol

runic urchin
slender nymph
rocky canyon
#

keep things smaller than u think u can manage

#

the last 20% of building a game takes 80% of all the time

rocky canyon
slender nymph
#

yes, that would be helpful

frozen plaza
#

I have a planet object and a small vehicle.. I put some gravity on the vehicle but the collision doesn't really work, the vehicle just falls into the planet..

It works with a different vehicle, but not with this one.. anyone know why?

slender nymph
#

not really enough info, but at a guess i'd say your collider is a trigger which means no physical collisions

rocky canyon
# slender nymph yes, that would be helpful

its not elegant but it works..cs [SpawnButton("SPAWN ALPHA")] public void SpawnAlpha() { // spawn a random alpha type. Index between 0 - amount of Alpha types Instantiate(typeAlpha[Random.Range(0, typeAlpha.Length)], transform.position, Quaternion.identity); }
https://paste.myst.rs/ju80tyw2

  • SpawnButtonAttribute.cs
  • SpawnButtonEditor.cs
#

@slender nymph sorry, i didnt notice u said UIToolkit until after i started pasting 😭

#

it is infact not the UIToolkit. but figured u might wanna look anyway.. sorry

#

works for what i need it for tho..
just SpawnButton[] w/ a boolean for whether its playmode only.. or both editor/play mode

#

i just wanted to get rid of NaughtyAttributes since i've been seeing editor issues that I can't really pinpoint.. and my most extensive editor manipulations come from NA

slender nymph
#

a lot of issues i've had with NA is due to the custom inspector applied to all MBs to make some of their attributes work. The problem I've run into with making the button attribute work with UITK is doing it without creating a custom inspector for all monobehaviors, but since property drawers don't work for methods that may be the route i have to go

rocky canyon
#

ya, im not too savvy when it comes to reflection.. i looked thru NA's code.. and asked some of my friends to help me get this working.. so far soo good

#

no performance issues as of yet

#

the only real issue i have is if i update the buttons while the inspector is open The styles get all messy and colors get inverted or something odd like that

#

just toggle to collapse and reopen, and the buttons fix themselves

#

im sure thats a simple fix.. but beyond me for now

slender nymph
#

actually, thinking about it i might be able to use a source generator to only create custom inspectors for the types that actually use the button attribute. i imagine that would end up more convoluted than just a custom inspector for MB, but might at least reduce the number of potential issues caused by the super generalized custom inspector. i'll have to do some tinkering with the two options to see which works better

#

or see if there is just a better solution than either of those

rocky canyon
#

its probably b/c buttons are already drawn there.. but its usually not this smooth..

rocky canyon
slender nymph
#

yeah pretty much lol

rocky canyon
#

is that what im gathering?

rocky canyon
#

if u do bite the bullet and build ur own.. HMU if thers anything that could improve mine

#

i'd greatly appreciate it.. and the learning better alternatives of it all

rustic maple
rocky canyon
near wadi
#

Argh!
EditorGUILayout.LabelField("Node:", EditorStyles.whiteBoldLabel); remains black color text, but bold.
EditorGUILayout.LabelField("Node:", EditorStyles.whiteLabel); works as expected
Bug report has been filed

restive nacelle
#

does anyone have any good tutorials for how to make a slot machine in unity, my game takes place in las vegas so i felt it was neccesary to make one

cosmic dagger
restive nacelle
#

all the ones i can find are from many years ago

#

I know how to make one in other langauges besides c# but then idk how to implement it

cosmic dagger
#

most tutorials are years+ old. that shouldn't matter . . .

wintry quarry
#

at a basic level, it's just a static 3d model

restive nacelle
cosmic dagger
#

did you try it and check if it worked?

restive nacelle
#

2d*

#

so just a ui really

#

of a slot machine gui

rich adder
restive nacelle
#

and this is my first project

meager gust
#

theres tutorials all over the internet for basic unity stuff

rich adder
restive nacelle
#

so heres what i decided to do now

rich adder
#

same concepts can usually be always applied thorough diff project types

restive nacelle
#

i made a slot mcahine in html

#

and im wondering how to import that into unity

#

idk how

meager gust
#

yeahhhhhhh

#

dont do that. you'll need to redo it in unity. those are two completely different concepts.

restive nacelle
#

especially because like i would have to port variables over

#

atp im considerign switching to a js framework

rich adder
#

html by itself does nothing useful you mean JS ?

restive nacelle
#

i made a slot machine in there

#

with a tutorial

rich adder
#

if you are able to write in JS c# wont be that much different

restive nacelle
rich adder
#

the concept is the same, esp if you choose a Random like class

deft grail
restive nacelle
#

only language im good at is python

deft grail
#

its all basically the same anyway, the language doesnt matter for basics much

rich adder
restive nacelle
rich adder
#

start with the basics types, operations, and whatnot. Go on from there
(imo start without a GUI and use console app from .NET )
https://docs.microsoft.com/dotnet/csharp/tutorials/intro-to-csharp/index

wicked pulsar
#

Hey guys! Is anyone here familiar with Timeline and Playables? I'm trying to create a basic system to write subtitles to a TextMeshProUGUI component, but the API seems to have changed so much over the past 4 years, that I'm not sure how to make heads or tails of it. Here is a sample of my controller that I use to affect changes to the on-screen visuals. How can I control this from Timeline?

{
    public static ClosedCaptions I { get; private set; }
    public static event ClosedCaptionsHandler onNarration;
    public static event ClosedCaptionsHandler onDescribedAudio;

    public delegate void ClosedCaptionsHandler(string source, string text, float duration);

    public NarrationLabelMode narrationLabelMode = NarrationLabelMode.Header;
    public enum NarrationLabelMode
    {
        Header,
        Inline,
        InlineCapitalized
    }

    private void Awake()
    {
        I ??= this;
    }

    public void Narration(string source, string text, float duration)
    {
        switch (narrationLabelMode)
        {
            case NarrationLabelMode.Header:
                onNarration?.Invoke(source, text, duration);
                break;

            case NarrationLabelMode.Inline:
                onNarration?.Invoke(null, $"[{source}] {text}", duration);
                break;

            case NarrationLabelMode.InlineCapitalized:
                onNarration?.Invoke(null, $"[{source.ToUpper()}] {text}", duration);
                break;
        }
    }
}```
rich adder
wicked pulsar
rich adder
wicked pulsar
rich adder
queen adder
#

Can 2D physics queries (circles) be rotated so that it lays flat in the XZ plane?

rich adder
#

dont think so because 2D colliders are only XY

wicked pulsar
cosmic dagger
primal flare
#

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

public class GameMenuMaganer : MonoBehaviour
{
public GameObject menu;
public InputActionProperty showButton;

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

}

// Update is called once per frame
void Update()
{
    if (showButton.action.WasPressedThisFrame())
    {
        menu.SetActive(!menu.activeSelf);
    }
}

}

Y IS THIS WRONG
i was watching this vid
https://www.youtube.com/watch?v=yhB921bDLYA&list=PLpEoiloH-4eP-OKItF8XNJ8y8e1asOJud&index=8

The episode 7 of the tutorial series that will teach you everything about VR interaction.

❤️ Support on Patreon : https://www.patreon.com/ValemVR
🔔 Subscribe for more Unity Tutorials : https://www.youtube.com/@ValemTutorials?sub_confirmation=1
🌍 Discord : https://discord.gg/5uhRegs
🐦Twitter : https://twitter.com/valemvr?lang=en
👍 Main Channel :...

▶ Play video
primal flare
rich adder
near wadi
eternal falconBOT
limber remnant
#

I was wondering if someone could help me with something. So I am using cinemachine to create a dolly track and Camera. I then want to move the camera to each of the way points by a button press. But for some reason I can't seem to get it to work properly. I think the code itself should work but when I go to attach the dolly track it just won't let me do it. And only keep saying that there's none available.

wintry quarry
#

The track wouldn't go there

#

A dolly would

queen adder
#

Does unity support multi language ? For example, can "using UnityEngine" instead be written in japanese ?

#

or it is strict latin and english ?

short hazel
queen adder
short hazel
#

Yes

queen adder
#

Okay thanks

limber remnant
#

Because I tried to putting the camera in there which is a dolly camera but that didn't work

static cedar
#
[ExecuteInEditMode]
public class InvertMaskingImage : UIBehaviour, IMaterialModifier
{
    [NonSerialized] private MaskableGraphic? graphic;
    private MaskableGraphic? CheckedGraphic
    {
        get
        {
            if (graphic == null) graphic = GetComponent<MaskableGraphic>();
            return graphic;
        }
    }

    public Material GetModifiedMaterial(Material baseMaterial)
    {
        if (CheckedGraphic == null) return baseMaterial;
        if (CheckedGraphic is MaskableGraphic image && !image.maskable) return baseMaterial;

        int id = baseMaterial.GetInstanceID();
        if (id >= 0)
        {
            Debug.LogError("Material is not an instance. Gonna oof ur project if this continues. Not bothering to copy either.");
            return baseMaterial;
        }

        if (isActiveAndEnabled) baseMaterial.SetFloat("_StencilComp", (float)CompareFunction.NotEqual);
        else baseMaterial.SetFloat("_StencilComp", (float)CompareFunction.Equal);
        return baseMaterial;
    }

    protected override void OnEnable() => CheckedGraphic?.SetMaterialDirty();
    protected override void OnDisable() => CheckedGraphic?.SetMaterialDirty();
}

Am i playing with fire with this script? UnityChanThink
I'm asking if this is enough checks so as to not inadvertently make the entirety of ui invisible.

#

What i really wanna check if the parent is a Mask and it's active.

#

So it's more decently full proof.

autumn gull
#

how do i fix?
MissingComponentException: There is no 'Animator' attached to the "Player" game object, but a script is trying to access it.
You probably need to add a Animator to the game object "Player". Or your script needs to check if the component is attached before using it.

keen dew
#

You probably need to add a Animator to the game object "Player"

autumn gull
autumn gull
#

but im not sure how

keen dew
#

Remove the getcomponent call, use [SerializeField] private Animator animator; instead and drag the animator you want into the field in the inspector

autumn gull
keen dew
#

Right, drag that object into the field

autumn gull
keen dew
#

Yes, the one that has the animator you want to use

autumn gull
#

but it gives me an error

autumn gull
keen dew
#

You put it in the wrong place

autumn gull
keen dew
#

No, replace line 14 with it. Delete line 19

autumn gull
autumn gull
#

its on loop time

#

ok i made run work somehow

frozen plaza
#

when I save my file, unity reloads the domain. when I then enter play mode it reloads again.. can I change this so it does not refresh on save but only on window activation (and going straight into play mode with one reload if possible)?

teal viper
#

Also, you can disable domain and scene reload on play in the editor preferences(or was it project settings🤔)

frozen plaza
#

I think at some point I enabled it to refresh on save but now with more stuff going on that really slows down iteration times

I need it to refresh before going into play ofc and also when activating the window in case some changes in editor space happened

teal viper
frozen plaza
#

unfortunate.. but ok, thanks

verbal dome
#

You could maybe write an editor script that recompiles scripts when entering playmode, though.

frozen plaza
#

yea, been thinking about ways to make this happen but at this point in time I don't want to spend too much effort in setting up dev environment when the time save isn't significant enough

astral falcon
#

I guess, making your own play button would be the most simple solution

uncut lantern
#

Hi I am kinda new can someone help me with making my 2d player move?(I have the code for movement) I can't figure out how to connect it to my player

astral falcon
uncut lantern
astral falcon
eternal falconBOT
autumn gull
#

Guys i made a movement that works perfectly but theres a problem. idk how to make it jump when i press space (and make it do an animation) or when i press shift i go faster. how do i do that?

#

i can show the code in dms

#

or here

upper egret
#

I know this is a very rookie question but what is the difference between var and float

languid spire
#

var can represent any type and is resolved by the compiler

hexed terrace
upper egret
queen adder
#

Is it possible to load new scene at runtime without building it to assetbundle ? I mean load the new scene from .unity file at runtime

autumn gull
hexed terrace
#

Or use one of the other billion "how to jump" tutorials available..

burnt vapor
#

Instead of fixing your issue, focus on configuring your !ide first. Then continue your issue. It will be much easier for you and others when your editor is configured.

eternal falconBOT
cedar prairie
#

Whenever my object collides with another object it then starts moving in a random direction forever and i dont know why

verbal dome
silk night
cedar prairie
verbal dome
#

I'm assuming you have a rigidbody?

cedar prairie
#

Yeah

#

Ik its the rigid body doin it

verbal dome
#

This is why you should not use transform to move a RB

#

Use rb.velocity/AddForce instead

cedar prairie
#

I tried using addForce but it just fucks me because it wont stop unless i do an opposite force and it sucks

verbal dome
#

Like Sidia said, if there's no external forces (drag, gravity, friction) then it will indeed keep moving "forever"

silk night
#

is it sliding across a floor or are you "in space"?

cedar prairie
cedar prairie
silk night
#

then why would it slow down? if you throw something in space it wont stop either 😄

cedar prairie
wintry quarry
verbal dome
cedar prairie
verbal dome
#

You could directly edit the velocity if you want precise movement

night valve
silk night
#

Simulating air drag is not just a checkbox sadly, you will have to write a script that slows objects

cedar prairie
verbal dome
silk night
silk night
verbal dome
#

Brainfart 🤷‍♂️

#

@cedar prairie If you want you can manually set the velocity in each FixedUpdate

#

Or just use AddForce if that suits you better

cedar prairie
#

Gah

#

Thanks for the help btw,

#

Oh wait so insted of add force its rb.velocity?

night valve
verbal dome
#

velocity is a Vector3 (or Vector2 in 2D) property and AddForce is a method

cedar prairie
verbal dome
#

No

#

I mean you can use either one to move the rigidbody, so in that sense yeah

limber remnant
# wintry quarry The cart is the dolly

That's what I thought as well. But for whatever reason it's not letting me put the cart in there. So I wasn't sure if there's some sort of setting I need to do or something.

silk night
cedar prairie
#

Right so since im utilizing the camera for its movement ill prolly want AddForce

silk night
#

uhh ok now might be the time you describe what you are trying to do, this got way too confusing with just a general problem description 😄

cedar prairie
#

So right its a little space ship thats floating at a set/locked Y coord. Im makin a game that's based around destruction n like physics so i might move the ship through other objects. Its supposed to be moved with w,a,s,d but the camera controlls the direction forwards is

silk night
#

ok then you have multiple possibilities:

  • Make the ship kinematic and move it on FixedUpdate loop, that way other objects cant move your ship
  • Add a drag or script way to slowly break from any collision events
  • Let the user figure out how to recover from a collision via controls
#

if you just want to break your other objects in the scene the drag option should be sufficient

cedar prairie
#

Yah ill prolly try em n see what i prefer thanks for the help

queen adder
#

im trying to save some data to a json object. the structure looks something like..

public class savedata { 
//save info here
public scriptableobject referenceToSOHere;
}

the problem however, is that the scriptable object holds a reference to a prefab and throws the following error
JsonSerializationException: Self referencing loop detected for property 'gameObject' with type 'UnityEngine.GameObject'.

what would be the best way to prevent this from happening?

wintry quarry
#

you either need to:

  • Make a custom serializer for your SO
  • Serialize some kind of identifier you can use to look up the SO instead
#

It's also not clear which serialization framework you're using here. Newtonsoft?

queen adder
#

yeah newtonsoft in this case

wintry quarry
#

You need to carefully think about what your intention is here. Presumably your ScriptableObject is an asset in the project right? So even if you properly manage to serialize it to JSON, you're not going to have that actual reference back when you deserialize

queen adder
#

yeah im storing general stat related information of an item in the scriptableobject, so things like, name, description, icon, stats of that item, and then the prefab directly related to it.

wintry quarry
#

right so - is the SO something that changes over the course of the game? Or is it basically a reference object that contains unchanging data

queen adder
#

unchanged data.

wintry quarry
#

if it's the former, you will want to fully serialize it here.
If the latter, you will want to serialize only a reference to it

queen adder
#

the refrence to the save data will change over the course of the game, but the data inside of the so is static and never changes.

wintry quarry
#

You could either use the Addressables package, or index them by some kind of ID so you can look them up yourself

#

and then basically your JSON should contain only that identifier

queen adder
#

addressable package isnt something i have used before, but based on looking it up, is it basically a database of assets, and instead of referencing the scriptable object, in my case, i would instead use an assetreference which can be serialized?

wintry quarry
#

In a nutshell, yes.

queen adder
#

i'll take a peak and see if i can easily change how things are loaded/saved/referenced.

#

thanks

wintry quarry
queen adder
rancid tinsel
#

whats this about?

#

am i being stupid and its not TMPro?

polar acorn
#

Do you have the package installed

burnt vapor
polar acorn
#

and is this an error in Unity or just in the IDE?

rancid tinsel
burnt vapor
rancid tinsel
#

so here?

burnt vapor
#

Sorry, haven't used Unity in a while

#

TextMeshPro should have an assembly definition of its own. Drag its reference into your assembly definition

rancid tinsel
#

yeah that fixed it

#

thank you!

dim yew
#

unsure why the ray is still getting the layout object here. i tried to mask it out and it doesn't seem to work

#

raycasts are really causing me issue right now

polar acorn
stiff birch
#

Your mask should exclude layout if you want to ignore this layer

dim yew
#

ok i am VERY misinformed on layermasks then

#

apologies

polar acorn
#

Yes, those are the layers you want to interact with

dim yew
#

is there an easy way to do that? or shoudl i read up on them

stiff birch
#

Does not say much. LayerMask are the layers you actually care about.

dim yew
#

thanks a bunch

rancid tinsel
#

is there a way to find a gameobject by its transform position?

polar acorn
#

Does it have a collider?

rancid tinsel
#

yes a box collider

polar acorn
rancid tinsel
#

how would this work though, like if it hits multiple colliders how would i know which is which

polar acorn
#

Which one do you want

rancid tinsel
#

im making a mine sweeper clone, so i want to check the 8 colliders around a block

#

but im prob doing it super inefficiently

polar acorn
#

In that case, you should have an array or grid instead, and then just get the objects at the bordering coordinates

#

position should not be a factor here

slender nymph
rugged gulch
#

my bad

queen adder
# wintry quarry You might need something like this btw, to convince newtonsoft to work with Addr...

was looking into this a bit more, but, how unsafe would it be to do the following? the saving would happen maybe once every X min and the loading would really only happen when triggered by the player. at max i would assume the player would be loading around 20~ assets on load, give or take.

public void LoadData() {
        string json = SaveAndLoadUtil.LoadJson(DATA_FILENAME);
        if (json == "") {
            return;
        }
        data = SaveAndLoadUtil.LoadObject<Data>(json);
        data.scriptableObject= AssetDatabase.LoadAssetAtPath<ScriptableObject>(data.scriptableObjectPath);
    }

    [Button]
    public void SaveData() {
        data.scriptableObjectPath = AssetDatabase.GetAssetPath(data.scriptableObject);
        SaveAndLoadUtil.SaveJson(DATA_FILENAME, data);
    }
wintry quarry
queen adder
#

cool, ill just go this route then. the addressables sound cool in theory but im just unfamiliar with them/cant figure out how to do it in a simple way without having to recode a bunch of extra stuff.

slender nymph
queen adder
#

and then in my data object i'm also using [JsonIgnore] on the actual references to the scriptable object.

#

and doing [HideInInspector] for the paths.

rustic maple
#

it only gives the error when the ai is in a frame of the camera

queen adder
slender nymph
#

wait was that supposed to be for runtime? because the AssetDatabase does not exist in a build

languid spire
queen adder
#

ah, well then, time to find a new altenrative/look into addressables again then

tulip nimbus
#

So this is kind of confusing me. My code works perfectly FINE, however i constantly keep getting this null reference message that i just cannot fix nor do i know what causes this, since the code runs perfectly fine and returns all values flawlessly

wintry quarry
tulip nimbus
#

That was quick! Thank you

#

found it and fixed it!

sleek notch
#

Hi, I'm sending messages between scripts and it is giving me an error: nameOfItem has no receiver. But as you can see, there is string. Can someone helo me?

wintry quarry
sleek notch
wintry quarry
#

Why are you using SendMessage

#

why not just call the function

#

.GetChild(...).GetComponent<MyScript>().nameOfItem(itemName)

wintry quarry
# sleek notch

anyway if you're getting that error here, the logical conclusion is that the child you're getting doesn't have that script attached to it

sleek notch
#

oh

polar acorn
# sleek notch

That would mean there's no script on that object that has a function called nameOfItem. One of the reasons you shouldn't use SendMessage, it has no compile-time checking of this

sleek notch
#

well

#

Actually I do

polar acorn
sleek notch
sleek notch
polar acorn
sleek notch
#

I don't lie. I have everything linked right. The Transform is linked right and then I Instantiate the object that really has the script where is the reference

#

I can give you screenshots

polar acorn
sleek notch
#

Okay. I'm gonna give you all screenshots

#

So. First is name of the script, second is where it is spawned and as you can see there is transform and third is linked script in the object that is being spawned

polar acorn
sleek notch
polar acorn
sleek notch
#

wdym?

polar acorn
#

I said to select the last child of RightPanelPlayerInv

sleek notch
polar acorn
# sleek notch

Show the full !code of inventoryItemManagement (can also take a look at that null reference while we're at it)

eternal falconBOT
amber nimbus
#

Hello, unity suggests this design pattern in one of their blogs. Now I am wondering how do I actually implement this? My only idea would be using a ton of events for each of the systems I make. I am not sure if this is a good idea or if I should stay away from making my whole code structure event based.

polar acorn
#

So, you would have an Input component that passes data to Movement, so now you can re-use that Movement script for things that aren't the player by changing which things call which functions

sleek notch
polar acorn
amber nimbus
polar acorn
#

Scripts contain classes

sleek notch
polar acorn
sleek notch
polar acorn
#

item hasn't been set

#

(Also if you're trying to call a function on the thing you just made, you should just use that object instead of getting the last child of the column)

amber nimbus
# polar acorn Scripts _contain_ classes

yeah i understand, but my PlayerMovement would have an if statement that checks an Input and if the input exists it would handle how the player should move. But I thought this picture wanted me to have a separate Input class and a separate Movement class meaning I would have the Input class fire events and the other classes subscribe to them I just dont know how events are performance wise, and if it is good pracitce to have a tone of events

sleek notch
#

can you describe it more?

polar acorn
polar acorn
polar acorn
sleek notch
#

Because there are more gameobjects for name or for kgs

#

so I need reference the name

polar acorn
polar acorn
# sleek notch Do you mean this?

If you are instantiating something solely to get a component from it, make the variable referencing the prefab of that type. Then Instantiate will return a reference to that component directly.

#

Basically, there's almost never a reason to have a variable of type GameObject. Use the type you actually want

sleek notch
#

the exact error still

#

wait

#

probably my bad

polar acorn
#

And you'll want to assign it's item variable directly

sleek notch
#

There is something wrong with TextMeshPro reference

#

or idk what is wrong. It will find the script but something went wrong...

rich adder
rancid tinsel
#

does this essentially mean it works like a singleton but for a variable/function?

#

or am i misunderstanding it

short hazel
# rancid tinsel or am i misunderstanding it

It's a bit less permissive than public. So if you declare something that's internal, other assemblies (= projects, DLLs when compiled) will not be able to access or use the thing

#

From least to most restrictive in order: public, internal, protected, private

rancid tinsel
#

im not sure i understand then

#

this might be a bad example but would cheatengine not be able to access internal, but could access public?

#

i know it reads memory but just for the sake of the example

languid spire
#

generally if you are using Unity then Internal is of no consequence as all Types will be inside the same dll

short hazel
rancid tinsel
#

i guess instead of cheatengine substitute just any external program

short hazel
#

If you used C# out of Unity, you may have created multiple projects in a single VS solution, each of them will be compiled to their own assembly

rancid tinsel
#

but could communicate if public?

short hazel
#

Something declared as internal in project A cannot be accessed from project B.

strong wren
rancid tinsel
#

so i guess maybe a better comparison would be that its like protected but instead of the inheritance hierarchy, its like a project hierarchy?

short hazel
#

Yep

#

You may use it without knowing btw, when you create types (classes, structs, etc.) that don't have any access modifiers eg. class Sample { }, they're internal by default.

rancid tinsel
short hazel
#

Like members without any mods are considered private

rancid tinsel
#

i was curious how that was handled actually because i assumed it would throw an error

short hazel
#

It's purely compile-time verifications. With Reflection you can access stuff that you're not meant to anyway

gusty cave
#

Hello. I'd like to make my game have different behavior when button V is pressed and when it is not.
The problem is that I don't know how to get the value of the button, as what I'm using bellow does not work.

private void OnFreeCameraPerformed(InputAction.CallbackContext context)
{
    bool buttonValue = context.ReadValue<bool>();
}
wintry quarry
#

however - depending on how you assigned thawt listener to the action - it may always be true.

#

like if you did freeCameraAction.performed += OnFreeCameraPerformed;

#

in that case you could also do:

freeCameraAction.canceled += OnFreeCameraPerformed;``` and it should work properly.
Or just write separate listeners:
```cs
freeCameraAction.started += _ => buttonValue  = true;
freeCameraAction.canceled += _ => buttonValue  = false;```
gusty cave
#

Thank you.

rustic maple
#

does anyone know the issue of this happening with my ai? i didnt make anything about the ai to stop when looking at it, it just happens through error, and it also happens when the ai is on the other side of the map

wintry quarry
steep rose
#

are you trying to set a destination outside of the current navmesh?

rustic maple
wintry quarry
#

it will show the full error message at the bottom

rustic maple
#

okay one se

#

and this is the script it refferences too:

wintry quarry
#

Please use a paste site 🙏

rustic maple
#

yep i know

#

was doing it

languid spire
# rustic maple was doing it

now read the message and read this

ai.enabled = false; //Slender's Nav Mesh Agent component will be disabled
            ai.speed = 0; //Slender's speed will equal to 0
            ai.SetDestination(transform.position);
wintry quarry
#

seems pretty clear

#

yeah

#

you're disabling the agent here

rustic maple
#

ohhhh

#

why tho? because i got this script from a tutorial i was following

wintry quarry
#

why what

#

How should we know why your random tutorial script is doing something 🤷‍♂️

#

they must have made a mistake

rustic maple
#

why in the script the agent needs to be disabled

rustic maple
#

so change the false vallue to true?

#

and the speed to 1

languid spire
#

just remove the line

wintry quarry
#

maybe?
Maybe double check your tutorial and make sure you copied it properl;y

#

or check the comments on the youtube video

#

people will have run into the same problem and fixed it.

rustic maple
#

alright ill let ya know

rustic maple
languid spire
#

omg. please engage your brain. the setting to false is causing the problem so that is the line to remove

rustic maple
#

This is part 9 of my tutorial series where I teach you guys how to make a Slender-like horror game in Unity. Be sure to stay tuned for part 10 which will most likely be the last part!

#Unity #Unity3D #gamedev

For more Unity tutorials like this or more videos in general - be sure to like, comment, and subscribe for more! 👍

Scripts:
https://dr...

▶ Play video
#

he added a "better" script to his ai