#archived-code-general

1 messages · Page 42 of 1

late lion
#

@zinc parrot Do you even need the original mesh data at runtime to perform the path tracing?

zinc parrot
#

technically no
I just A mesh data
and access to its tri buffers and such
or a way for getdata to not allocate and not free memory every time its run in the same frame

late lion
#

Due to the syncing you need to do with the GPU, I don't think it's possible to do it otherwise, even with a native plugin.

zinc parrot
#

unfortunately I cant do that as some objects need to be seperate
the only part thats creating extra data is when I call getdata

late lion
zinc parrot
#

because they are split between different gameobjects

zinc parrot
#

oooo? ill check it out!

late lion
#

This doesn't bypass the read/write flag.

#

It's just a more optimized API than the vertices and triangles arrays.

zinc parrot
#

heck

late lion
zinc parrot
#

damn ok

west lotus
#

I didn’t know that was a requirement

#

Required the read flag to be set

frozen surge
#

Anyone know if there's a way to stop shortcuts like Ctrl+S and Ctrl+W working in the browser when playing a unity webGL build?

zinc parrot
hexed pecan
#

Those SO's could still implement interfaces, you don't have to use one or the other

echo quartz
#

if I call Resources.Load on a resource that is already loaded, will unity realise this and just give me the thing that's already loaded in, or will it still fuck off to the disk?

idle meteor
#

I want to show profile photos of my Steam friends. But the first problem is that all the images are the same in this way, the second problem is that the images are upside down. Why does this happen?

drifting grail
#

Will changing CharacterController.velocity actually move the character controller? Or does it only return the velocity the character controller is moving at

zinc parrot
#

How can you tell if a user is manually rotating a thing? I have a thing that rotates an object, but I want to be able to rotate it manually as well and have that reflected

late lion
zinc parrot
#

but I cant do that because the script also modifies the rotation itself

late lion
#

I mean something like this:

private Quaternion previousRotation;

private void Start()
{
    previousRotation = transform.rotation;
}

private void Update()
{
    Quaternion delta = Quaternion.Inverse(previousRotation) * transform.rotation;

    Quaternion rotation = whatever;
    transform.rotation = rotation * delta;
    
    previousRotation = rotation;
}
#

The order of the Quaternion.Inverse might be different, I can never remember.

zinc parrot
#

hmmmmm ok ill try that
trying to rotate a light tho

modern creek
#

I'm having some super aggravating behaviour with dragging game objects around in scene mode in 2021.3.18f1 (didn't in 2021.3.3). Anyone else having this? Also the mouse cursor appears to be getting "stuck" on the wrong type (in my video it gets stuck on horizontal resizer)

safe abyss
#

Guys, in UGS, can we make a user create an account using custom email & address? I can't find it in authentication

merry sequoia
#

Hey, how do I start a coroutine if a condition is met, and then it plays untill another condition is met?

hexed pecan
#

Remember to wait in the loop (like yield return null), otherwise it might freeze

modern creek
#
private bool _isConditionMet = false;
private bool _isPlaying = false;
private void Update()
{
  if (!_isPlaying && _isConditionMet) StartCoroutine(MyCoroutine());
}
private IEnumerator MyCoroutine()
{
  _isPlaying = true;
  while (_isPlaying)
  {
      // .. do something
  }
  _isPlaying = false;
}
#

(or the while loop could check directly against the condition)

merry sequoia
#

You guys are a bunch of saviours, thank You very much.
I've been trying to approach my problem from so many different angles, and I think that this is the correct one. (Took me about 9 hours)

tawny jewel
#

hey, so basically i have a gameobject with a script, collider2d and rigidbody2d attached. when, for example, im moving the gameobject with rigidbody.moveposition everything works nicely, but when the body has no additional force from the script and falls using just gravity collision detection in ocollisionenter2d method is very delayed. any ideas how to fix that?

modern creek
#

increase gravity, mass, or scale

#

if the oncollisionenter isn't firing when you want, make your collider bigger

tawny jewel
hexed pecan
#

If you want physics responses you should move it with rb.AddForce or rb.velocity etc.

tawny jewel
#

it does for me

tawny jewel
tawny jewel
#

i want it to be moved just by gravity

#

without the unwanted delay ofc

hexed pecan
#

Hmm how are you noticing the delay?

#

You mean the collisions work normally but the OnCollisionEnter2D gets delayed?

tawny jewel
hexed pecan
#

Oh youre trying to ignore collisions when colliding?

tawny jewel
hexed pecan
#

I don't think it works very well. At the point when OnCollisionEnter is called, the collision has already happened.

hexed pecan
#

You can't cancel a collision afterwards if thats what youre trying to do

#

But you could store the velocity etc and try to replicate that

tawny jewel
hexed pecan
#

What exactly are you trying to achieve

#

What's the mechanic?

tawny jewel
#

its just that that when the object falls on the collider with gravity it takes it literal second to realise it collided

hexed pecan
tawny jewel
# hexed pecan What's the mechanic?

well its a part of the bigger script but thats irrelevant here as i basically for testing made a sepeate script with litterally just oncollisionenter method

hexed pecan
#

You could try to store the velocity (and angular velocity) and apply it back after the collision

tawny jewel
#

basically its a revive buff system for my floppy bird

hexed pecan
#

But is there a reason you don't ignore the collision beforehand?

#

You want the collision to happen?

tawny jewel
hexed pecan
tawny jewel
#

then it starts a coroutine and the collisions are occuring again after 4 seconds

hexed pecan
#

Can't you just set the bird's collider to trigger while isRevive is true?

tawny jewel
#

i could but i also want it to interact with other objects regardless if isrevive is true

#

i want it to ignore collsions just with layer 7 specifically

#

with is the pipes layer

hexed pecan
tawny jewel
#

i could technically make that work with ignoring layers as soon as the bool turns to true though ig

tawny jewel
hexed pecan
#

Yeah but ignore it when you set revive to true

#

Right?

#

Not when colliding

tawny jewel
#

i suppose i will, though it still gets me wondering why does the collision occur delayed when rigidbody free falls, in case ill have a simmilar issue in the future

hexed pecan
#

It's just a little quirk in the engine but theres multiple ways to get around it

tawny jewel
#

alright, that makes sense

hexed pecan
#

Another option is to have a layer for when you want to be immune, and swap the bird to that layer temporarily

#

And that layer would always ignore the pipes

tawny jewel
#

but just simple debug.log message appears delayed

hexed pecan
tawny jewel
#

its next to project as per default

shut bear
#

Not too sure in which channel i should post this but i have this common problem with my textures on my mesh. It's an exported model from blender with a simple generated UV Map. The texture is correct at some places (left of image) but the on other spots its really stretched. I've already put the wrap mode on repeat but that doesnt fix it. Anyone knows whats going on? Is it the UV Map that isnt correct?

autumn stratus
#

Anyone prefer JB Rider over VC/VCS . does it support CoPilot?

west sparrow
autumn stratus
#

cheers

plucky karma
delicate saffron
#

hey, when using the burst compiler are you unable to use structs inside of a job class?

#

im trying to use a struct to store data but it tells me its "unable to get field because is class type"

west lotus
#

Jobs are structs too

#

You cant use classes in jobs or a burst method

delicate saffron
#

oh

#

okay

west lotus
#

Any non-blitable type actually

delicate saffron
#

what makes a type non-blitable?

quartz folio
west lotus
delicate saffron
#

alright thanks

swift falcon
#

Is it alright to put a class and interface to the same script? Trying to fix disgusting code

public interface IIKillableBot
{
    public void AiDeath();
}

public class AIBullet : MonoBehaviour
{
    public bool red;
    public bool blue;


    private void OnCollisionEnter(Collision col)
    {

        col.transform.TryGetComponent(out RagBodyPart r);
        if (r)
        {
            if (blue)
            {
        ...
        ...
        ...
}```
somber nacelle
#

sure, but if you want to be able to add the MonoBehaviour to an object in the inspector is has to be the first type in the file

swift falcon
hybrid merlin
#

Anyone knows if Screen.dpi is reliable on desktop computers, and on WebGL?

somber nacelle
hybrid merlin
#

the order of definition is not important

#

but the name is. it has to be the same name as the file

cosmic ermine
#

I have my player's position locked to a grid, however if i constantly set the cameras position to the player's position it looks jittery and weird, as such I'm wondering what would be the best way to create a smooth transition from the cameras position to the player's position? Would lerp-ing between the cameras position to the players new position be a good way of doing this, or is there a better way?

cosmic ermine
opal pine
#

Hey guys. How can I change a layermask in code? Ive tried buildMask = LayerMask.NameToLayer("Ore"); but its not changing in the inspector.

cosmic rain
opal pine
#

I have my Ore layer set on a gameobject yes. But my issue is its not setting the inspector to what I want to set it in code. Because Im using raycast to check layer type and because i didnt want to make 50 + layermask variables. ive just made the one and want to update what its meant to be looking at based on what item is being searched for

#

So the build mask should be updated to Ore when its clicked and updated again when next button is pressed. I thought I would be able to change this inside the code since I want it to be dynamically controlled.

dim furnace
#

For some reason I get this error when I go in game

cosmic rain
cosmic rain
dim furnace
#

I have a camera on the player

cosmic rain
dim furnace
#

No

#

Ill add it

#

it bugs my game out

#

alot

cosmic rain
#

Well, that just means that you have other bugs🤷‍♂️

#

having a main camera shouldn't cause bugs

dusk apex
dim furnace
#

ill fix it

dusk apex
dim furnace
#

im aware

cosmic rain
dim furnace
#

no i make it destory the camera if !view is mine

dusk apex
#

And because of a tag UnityChanThink

dim furnace
#

ill work around it

near crown
cosmic rain
#

Unless that's what you want it to do

near crown
#

How do I fix its floating?

cosmic rain
#

Find the cause and eliminate it.

near crown
#

I wanna do a platformer, not a floater

cosmic rain
# near crown I wanna do a platformer, not a floater

Start from thinking logically:

  • unity rb doesn't float like that by default.
  • means that there's something on the object that causes it.
  • what components on the object could be affecting it's movement?
  • could it be the movement controller?
  • try disabling it.
  • did it fix it?
  • then that's the cause.
  • look into the component code and apply similar steps to the code as well.
near crown
#

I disabled my moving script and the rigidbody behaves the same

lucid valley
#

ChatGPT probably just made it up

#

Heres the forum post about the .Net upgrade (it'll probably also be .Net 7/8)

#

The built player should be this year hopefully

#

editor maybe another 1-2 years, depends on how much work

cosmic rain
near crown
#

well I guess I have to program my physics myself

cosmic ermine
cosmic rain
near crown
#

i dunno I wanted to make a game similar to SMB1, I dont think it will be easy but I don't find fixes to the weird rigidbody behaviour

#

I have tryed on other objects and it behaves the same

cosmic ermine
#

if you want to you could try doing verlet integration, which is somewhat simple to setup, and pretty performant, but if you can get Unity's rigidbodies working then you will have an easier time

cosmic rain
near crown
#

I did that with a square

cosmic rain
near crown
#

ok

#

(srry for the bad quality is my main monitor with that problem)

#

btw I think that 2d pixel perfect package might be somewhat involved

quartz folio
#

Chat GPT is confabulating, because it doesn't know anything. It's a language model, a predictive text engine. Using it to find facts is a waste of time, and asking about bullshit it makes up is against our conduct

near crown
near crown
#

I don't remember if this is a package that I have added or a default package

cosmic rain
near crown
#

I know

#

That is fine

#

since It is checking for the rigidbody

#

that I removed from Mario

#

dw about it

cosmic rain
#

Fix the error and try again. It just ads unneeded variables to the situation.

near crown
#

are you looking at the console or the square?

cosmic rain
#

Next thing to do is take a screenshot of your project - physics2d tab and project - time tab

near crown
#

where do I find physics2D tab?

cosmic rain
#

project settings - physics2D

near crown
#

Also now I removed and readded the rigidbody to Mario and the square behaves normally

cosmic rain
#

Then the issue is not with the rb

#

Share you movement controller code

near crown
#

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

public class MarioMove : MonoBehaviour
{
public int Ambient;
int Direction;
public float Horizontal;
public Rigidbody2D RB;
public float speed;
private float Speedresult;
void Awake()
{
RB = GetComponent<Rigidbody2D>();
}

void Update()
{
    if (Input.GetKeyDown(KeyCode.Alpha1))
    {
        Ambient = 1;
    }if (Input.GetKeyDown(KeyCode.Alpha2))
    {
        Ambient = 2;
    }if (Input.GetKeyDown(KeyCode.Alpha3))
    {
        Ambient = 3;
    }if (Input.GetKeyDown(KeyCode.Alpha4))
    {
        Ambient = 4;
    }
    Speedresult = speed * Horizontal;
    RB.AddForce(new Vector2(Speedresult * Time.deltaTime, 0f));
    //print(Horizontal);
}
public void Move(InputAction.CallbackContext context)
{
    Horizontal = context.ReadValue<Vector2>().x;
}

}

#

gtg for a bit

cosmic rain
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

fiery saddle
#

In custom editor you can set field to be as script in image or text field in image

#

anybody know how?

#

I know its something as "appear as editor" or something like that

#

but googleing doesnt help

dim furnace
#

For some reason my tilemap stops my player likes theres some weird collider

quartz folio
#

If you are making a custom editor you can display any serialized variable using a PropertyField

fiery saddle
quartz folio
#

That shows fields as disabled

#

If you are using IMGUI

dim furnace
#

How do i make it so no one can see the code of my unity games?

vagrant blade
#

You can't

dim furnace
#

u cant obfuscate at all?

delicate olive
#

How can I modify a rect transform delta size of an object

blackBorders.sizeDelta = new Vector2(2025, 1139);
#

that code doesn't work btw ^

vagrant blade
dim furnace
#

Alrighty

vagrant blade
#

This is a common question people get too hung up on. The majority of people don't care about your code, assuming you even have players to begin with. Focus on the important things first.

dim furnace
#

Ok

#

My main saving system is in binary anyways

maiden fractal
dim furnace
#

Yeah

dim furnace
#

why

maiden fractal
#

Read the article

mental rover
#

this doesn't really matter for games though, depending on what your game is doing - if your save system is just locally storing a state it really doesn't matter.
If you're importing saves from other anonymous users over the internet as a single binary file, maybe revisit

supple wigeon
#

Hi! How i can find closest object (bal) in front (cube.forward) of the cube, all balls are in a list and the target will be the red ball

maiden fractal
maiden fractal
supple wigeon
#

Yes

#

Some how it needs to be the first in front of the cube

maiden fractal
#

Highest value of Vector3.Dot(cube.forward, (ball.position - cube.position.normalized) is closest to being in front

dim furnace
#

Would saving data using this video: https://www.youtube.com/watch?v=XOjd_qU2Ido&ab_channel=Brackeys

Work on a photon room where it saves and loads your data?

Here's everything you need to know about saving game data in Unity!
► Go to https://expressvpn.com/brackeys , to take back your Internet
privacy TODAY and find out how you can get 3 months free.

● Easy Save: https://bit.ly/2BzgdXb

♥ Support Brackeys on Patreon: http://patreon.com/brackeys/

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

▶ Play video
maiden fractal
supple wigeon
#

@maiden fractal i'm trying this now...

#

not working...

maiden fractal
supple wigeon
#

@maiden fractal closestOne = balls.OrderBy((Transform t) => Vector3.Dot(transform.forward, (transform.position - t.position).normalized)).FirstOrDefault(); I think this works, at least with balls... now i will try on main script..

maiden fractal
#

@supple wigeon Id do this ```cs
highestDotProduct = -infinity
bestMatch = List[0]
For i = 0 to List.Length
dot = Dot(Cube.forward, (List[i] - Cube.position).normalized)
If dot > highestDotProduct
highestDotProduct = dot
bestMatch = List[i]

In the end `bestMatch` should be the closest to being in front
echo pelican
#

Hi guys! I've implemented stateMachine with Zenject. Can you take a look at it and tell me tell me what to redo, in other words can you make a small code-review? ( https://github.com/maxi2000138/State-Machine-with-Zenject.git )

GitHub

This is State Machine basic form using Zenject. You can add various services you need - GitHub - maxi2000138/State-Machine-with-Zenject: This is State Machine basic form using Zenject. You can add...

supple wigeon
#

@maiden fractal Thank you for help, Linq work in my case now i just need to set the balls.position.y = 0 and cube.pos.y = 0 in code to be on same plane

dense herald
#

Hi, how would you pull a GameObject to another GameObject? Kinda like a grappling hook where it pulls the player towards it.

delicate olive
dense herald
#

yeah

tepid hearth
#

when i instantiate a gameobject imported from blender which has two materials, one of them becomes white (picture). Why is this and how do i fix this?

#

element 0 is the one which has become white

tepid river
#

how do you guys handle colliders?
i have a spaceship and a ton of asteroids, some very large. do you use convex mesh colliders?
if so, for a complex shape like the ship, do you use multiple colliders, since they are restricted in shape and face count?

simple echo
#

I am trying to add the floor object to the Mesh renderer but its not happening

#

cant seem to drag and drop 'floor' to the mesh renderer inspector area

opal wagon
simple echo
opal wagon
#

I think you need actually a SpriteRenderer in this case

#

I mean chage the MeshRenderer variable to SpriteRenderer, since you're doing 2d stuff

hexed pecan
simple echo
stark plaza
#

Does it make sense to make a abstract class that inherits monobehaviour and has instance of all singletons inside to reduce verbosity instead of going every time GameManager.Instance.yadda
just GameManager.yadda?

leaden ice
leaden ice
opal wagon
# simple echo no

It depends on what you want, it's been a while since I've done serialization stuff, but it only for saving data afaik, as for the private, if you don't want the variable to show in inspector you make it private, otherwise public

tiny delta
#

For my game would it be better to store the player's stats (current and max health and mana) on their character script as a class with properties, or should I create a separate gameObject with a stat manager script?

#

I'm doing my best to get good practices while starting this game and learning unity so I don't have too many problems down the line.

tepid river
#

well they shouldnt be hardcoded into a class. ideally they shouldnt depend on the class in any ways

#

the class aka implementation should depend on the higher level functioanlity = the stats

#

but during runtime i would store them in the class, or in a container object in the class (for easier serialization)

thorny spindle
#

Depends what you want to access the variable

tiny delta
# tepid river well they shouldnt be hardcoded into a class. ideally they shouldnt depend on th...

I assume by this you mean just don't store the starting stats in the class (eg. no magic numbers)?

public class PlayerStats
    {
        public float maxHealthStat = 100;
    }

What I currently have is in my ControlCharacter script I have

public class PlayerStats
{
  public float maxHealthStat;
}

and in Start I have stats.maxManaStat = maxMana; where maxMana is declared above as [SerializeField] private string maxMana;

This is all reasonable?

thorny spindle
#

I mean if I had a bunch of things that had stats I might just make some kind of ICharacter class for simple games

tepid river
# tiny delta I assume by this you mean just don't store the starting stats in the class (eg. ...

yeah looks alright. i personally try to use as little monobehaviour builtins as possible, like Start().
its all sideeffects that get triggered outside of my control.

generally, you might have a situation where the player doesnt start at full health at scene start.
so make an "initPlayer()" method that resets all stats, and call that in start().
that way you can call if from somewhere else or easily disable it in start

thorny spindle
#

So MainCharacter : ICharacter. MobEnemy : ICharacter

tiny delta
#

My bad, I hadn't seen the second part of your message

tepid river
#

thats becasue i edited it lol

thorny spindle
#

Having a stat manager class for ONLY your character stats sounds unweildy somehow. But maybe your character stats are complicated enough to warrant it

tepid river
#

also:
InitPlayer() is a shit name for a method, its meainless..

#

more like SetPlayerStatsToDefault() or SetPlayerStats(Stats.default)

thorny spindle
#

Just make life hard for everyone

soft hare
#

can some one helps me in code advanced

thorny spindle
#

//Is for inital character stats (ICS)
private struct ICS() {
...
}

#

that would be amazing

spice schooner
#

hello, im not entirely sure where to ask this but i have this weird issue where after creating a spline at the start of a game (through the start function in code by adding a new knot for each position) the spline is not curved until i click something on the spline component in the inspector, and updating anything on the spline component through code doesnt work. if i dont press anything on the spline component it stays as a linear spline.

splineContainer.Spline = new();
        foreach (Transform space in gameplayManager.boardRoute)
        {
            splineContainer.Spline.Add(new BezierKnot(space.position));
        }
        splineContainer.Spline.EditType = SplineType.CatmullRom;
languid pendant
#

When using OnMouseEnter() with the Scenes Time.timeScale = 0f, if I update the position of the gameObject with the OnMouseEnter()'s position by just doing .position = newPosition on the gameObjects transform, OnMouseEnter() will register when the mouse is over the original position of the gameObject, and it doesn't seem to update where it's position if for OnMouseEnter() until the scenes's timeScale is made greater than 0. Any idea how to force update the position of the gameObject for the OnMouseEnter() without changing the timeScale from 0?

soft hare
#

can i get some help in advanced code

thorny spindle
#

Until I hit something in the inspector and Unity corrects stuff

soft hare
#

sharramon can you help me

warm wren
soft hare
#

ok look my problem is quit complicated i want to show it to you using share screen in a vc

#

quite

spice schooner
soft hare
#

flo

#

can you help me in a vc

jaunty gust
#

?

#

I don't know how to solve your problem sorry

soft hare
#

look i have a problem in a binary save system code and i want get help

delicate olive
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

jaunty gust
#

I don't speak english sorry

soft hare
#

do you spwak spanish?

jaunty gust
#

nah

#

sorry

soft hare
#

what do you speak arbaic

jaunty gust
#

french

soft hare
#

nice i know some french ill try

delicate olive
#

https://gdl.space/husafalohi.cs

I bet the solution is right under my eyes but I just can't find it
<at line: 38> Object reference not set to an instance of an object

EDIT: spaghetti code

sleek bough
#

@soft hare Post you problem with full description. Do not pin people to your questions or cross-post

soft hare
#

ok

#

i have a problem that i cant explain i create a directory for a binary save system but it cant find it

soft hare
#

okay

jaunty gust
#

In a for loop, I have to do for each iteration an operation on an object's transform and on the gameobject itself.
what is better :

  • first : Transform myobj = stg
  • then : do stg with transform
  • then : do stg with transform.gameObject

OR

  • first : GameObject myobj = stg
  • then : do stg with gameObject
  • then : do stg with gameObject.transform

I know the performance gain must be pretty small but i need to do this for thousand of objects.
Thanks a lot !

sleek bough
soft hare
#

so do i post the error its quite long

delicate olive
sleek bough
#

Show the full error

delicate olive
#

uhh it's so reliant on other scripts so please be ready to use your brain

soft hare
#

and

delicate olive
sleek bough
delicate olive
#

okay thanks will do

soft hare
#

i posted full errors

sleek bough
soft hare
#

i know what they mean

sleek bough
#

@delicate olive Should not use Find methods as well. Create proper reference in the inspector and link it.

soft hare
#

but i dont know what is causing them i am creating a directory file anyways

sleek bough
#

Then you'll know that object reference exists

soft hare
#

DirectoryNotFoundException: Could not find a part of the path "C:\Users\HASSAN\AppData\LocalLow\KEll\idle\saves\SaveSystem.txt".

#

here is my code

sleek bough
#

!code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

jaunty gust
#

and see what it says

soft hare
#

i tried it says it doesn't exists but i am not trying to access that place anyways

open knot
#

I have a movement script that uses a character controller and no rigidbody, how can I make it so i can change how much acceleration is when you start/stop moving.

heres my code:

#

I know i can change GetAxis to GetAxisRaw to delete all acceleration but id like to be able to change how much acceleration i get

soft hare
elder hollow
#
using System.Collections.Generic;
using UnityEngine;

public class enemy : MonoBehaviour
{

    public int maxHealth = 100;
    public int currentHealth;


    [SerializeField] private Transform _center;
    [SerializeField] private float _knockbackVel = 20f;
    public Rigidbody2D rb;

    GameObject UIText;

    public CollisionDetectionMode2D collisionDetectionMode;
    void Start()
    {
        currentHealth = maxHealth;
        rb.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
        UIText = this.gameObject.transform.GetChild(0).GetChild(0).gameObject;
    }

    public void TakeDamage(int damage)
    {
        currentHealth += damage;
        UIText.GetComponent<Animator>().SetTrigger("textChange");
    }


    public void Knockback(Transform t)
    {
        var dir = _center.position - t.position;
        rb.velocity = dir.normalized * _knockbackVel * currentHealth / 10;
    }
}

im making a platformer fighter and i want to make it so when the player collides with a wall while the knockback velocity is active he bounces off of it

#

using a tilemap for the platforms

rare lodge
#

Hello guys i wanna ask for performance reasons 🙂 my trees im not able to put in Terrain painting because tree has stump and Top , unity dont allow me use this kind of mesh prefab ..... so if i put tress as objects in to the scene of course not thousands because alll are chopable will have it big impact on performance?

delicate olive
#

Issue: can't press the "Restart" button even though (I believe..) it's interactable

Also, during the video the errors at the bottom have nothing to do with this problem, they're just the enemies trying to move towards a null object

lucid valley
#

Also just try fixing the other errors first, then at least you know 100% that they are not preventing the button logic running somehow

delicate olive
delicate olive
lucid valley
delicate olive
#

like
if (playerObject != null)
{

}

lucid valley
#

you'd have to show the erroring line for me to give you something more exact

#

yeah

delicate olive
#

okay but it gave me errors before for trying to check a null object for null

#

idk how to explain it lol

lucid valley
#

show

#

something like this would still error playerObject.transform != null

delicate olive
#

oh yeah that

lucid valley
#

just check playerObject != null then

delicate olive
# lucid valley just check `playerObject != null` then

will do

and FYI this is the error line (on the enemy script)

void Update()
    {
        if (player.position != null)  // Error Here
        {
            Vector3 moveDirection = player.position - transform.position;
            float moveAngle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
            rb.rotation = moveAngle;
            moveDirection.Normalize();
            movement = moveDirection;
        }
    }
lucid valley
#

player != null

delicate olive
#

but wait I really need that player.position check to stay there

#

do I just nest if statements

lucid valley
#

what is position?

#

just a monobehaviour script you've made?

#

or is it some property to get the transform

delicate olive
#

idk I modified this last time like 7 days ago and that's also when I started unity so it's kinda spaghetti

#

I don't remember why I added that

#

wait I'll try replacing it with what you said b4

lucid valley
#
    void Update()
    {
        if (player == null) return;
        if (player.position == null) return;
            
        Vector3 moveDirection = player.position - transform.position;
        float moveAngle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
        rb.rotation = moveAngle;
        moveDirection.Normalize();
        movement = moveDirection;
    }
#

avoid the nesting

#

there is better ways to do this

delicate olive
#

alr

lucid valley
#

but i think it'll be slightly above your current level (as you can chain null checks in C# but with Unity you have to do some extra work to make it safe)

#

also you might want to turn those scripts off instead of returning but that is more advanced

delicate olive
#

first though I'll check if I'd even need that player.position check in there

#

Yeah I didn't even need that

#

Now the errors are gone but the respawn button issue remains the same

lucid valley
#

no errors?

#

how are you detecting the button click?

#

new input or old input system? (i've only used old, so i might not be too much help)

delicate olive
#

legacy

#

this is the RespawnButton script

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class RestartButton : MonoBehaviour
{
    [SerializeField] Button restartButton;

    private void Start()
    {
        restartButton.onClick.AddListener(RestartScene);
    }

    private void RestartScene()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}
lucid valley
#

add a log in the RestartScene to check if it runs

delicate olive
#

okay

lucid valley
#

just fyi, you can subscribe like this in code or you can set it up in the inspector on the button component (RestartScene() would need to be public)

delicate olive
#

Also the debug.log didn't run, as expected

lucid valley
#

huh

#

add a log to the start

#

you have attached this to a gameobject right?

delicate olive
#

yep

#

I don't think it's a problem with the script though, since the button isn't even highlighting when I drag my mouse over it

#

Tried changing the highlight color to something very visible (like red) so that's where I got this info from

lucid valley
#

show the inspector of the button script

delicate olive
#

will do brb

delicate olive
#

I'll ask chatgpt to see what it can give

lucid valley
# delicate olive

just random guess, but you tried to add a onclick function to the button, press the - sign and remove it

#

i'm not sure why that would interfere but you never know

delicate olive
#

oh that's smart, I'll playtest

onyx sun
#

Ou wow cool

delicate olive
#

does nothing ://

#

well at least it improved the performance by like 1kb

#

disabling all the other UIs (shopui, scoreboardui) also did nothing

lucid valley
#

humm

delicate olive
#

I'll try creating a new button at the same location to see what would happen

#

other button also doesn't work

lucid valley
#

if you set it up using the inspector does it work?

delicate olive
#

yeah I set it to be a top child of the highest "Canvas" object

lucid valley
#

i mean like using the OnClick on the button script in the inspector instead of subscribing in code

delicate olive
#

I'll try, but I don't think that would affect the thing

lucid valley
#

yeah, i can't see any obvious reason why it's not working currently

delicate olive
#

okay so it's not just me

lucid valley
#

do you have nested canvases?

delicate olive
#

yep

#

like 3 I think

#

wait no I don't

#

I have nested canvas groups to control different alpha levels on the animation

#

but not nested canvases

#

also there's no function to choose when I tried your possible fix

modified script:

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class RestartButton : MonoBehaviour
{
    [SerializeField] Button restartButton;

    private void Start()
    {
        restartButton.onClick.AddListener(RestartScene);
    }

    public void RestartScene()
    {
        Debug.Log("RestartScene");
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}
lucid valley
#

you want the restart button script

delicate olive
#

oh yeah that class is a RestartButton

lucid valley
#

not respawn script

simple egret
#

"If you see MonoScript you did it wrong"
Drag the script from the object it's attached to in the scene, not from your project files

delicate olive
#

hmm okay

lucid valley
buoyant crane
lucid valley
#

ah true could be that

simple egret
#

You can also change the button's hover color to something noticeable, then hover the button

#

If you don't see the color, events aren't reaching it

delicate olive
#

still did nothing

simple egret
#

Does it turn bright red when you hover over it?

delicate olive
#

nope nothing happens

#

all other buttons work though (like the shopui buttons)

buoyant crane
delicate olive
simple egret
#

Then something prevents the events from reaching it. Like an object over it

delicate olive
#

do I turn on debug mode

buoyant crane
#

make sure you are in play mode while doing it

delicate olive
#

yeah I was I believe

simple egret
#

The little debug interface of the event system will appear at the bottom of the Inspector while in play mode

#

You'll be able to see what it detects there

delicate olive
#

wait I'll record this because it's difficult to explain

#

Current Focused Game Object on Hierarchy doesn't show the button, but shows everything else just fine

simple egret
#

Yeah something is clearly in front of the button

delicate olive
#

I bet

#

what if I move it to some other ui like the shopui and see if it works there

simple egret
#

That's a way to troubleshoot yeah

#

You could also disable everything except the button and the event system, and activate the other objects one by one until it doesn't detect the clicks anymore. At that point you'll have the object that causes the issue

delicate olive
#

and also moving it up in the hierarchy did nothing

simple egret
#

Yep so the shop UI is the one blocking it

delicate olive
#

yeah something must be blocking it

#

wait that one?

simple egret
#

Well yes

#

If you put it in, it works. Take it out and it fails

delicate olive
#

but the canvas of the shopui is disabled (unless I press tab) so it can't be blocking it

simple egret
#

Disabled how?

delicate olive
simple egret
#

Canvas Group with alpha turned down to zero : the object is still there

mossy snow
#

eh I think somebody got it earlier, nested canvas without a GraphicRaycaster. Type "t:Canvas" in scene hierarchy search window

simple egret
# delicate olive

Yeah the object will still be there. Disable the whole GameObject, not some script

delicate olive
simple egret
#

obj.SetActive(false);

delicate olive
#

wait didn't I already try that before

#

disabling all UI's but nothing happening

soft hare
#

can some one already help me

#

pls i sent the error but no on responded

mossy snow
#

I assume that enabled Canvas is UI/RespawnManager/Canvas. Look at it and confirm it has a GraphicRaycaster on it

soft hare
#

xevil can you help

simple egret
mossy snow
# soft hare xevil can you help

your error explains itself, there isn't anything to help with. Some part of your path doesn't exist. I'm going to guess the saves directory

simple egret
# delicate olive yep there it is

Just disable the whole object. Disabling the Canvas component will just disable that component, other objects will still be in the way. That's not a raycaster issue

delicate olive
#

"Blocks Raycasts = false"

#

on the shopui it was set to true, and when i set it to false, the shopui buttons also stopped working

soft hare
delicate olive
#

so lemme try with this button

simple egret
#

Setting it to false just tells the event system to not detect anything, even if the objects are there

delicate olive
#

Yep now it works lol

simple egret
#

Still not the preferred solution though, just disable the shop ui object

delicate olive
delicate olive
#

Anyways thanks for the help guys

hasty blaze
#

what's that?

simple egret
#

Your TextMeshPro package acting up

#

It's not your own code that's failing

#

Restart Unity if it makes something fail gameplay-wise

#

Otherwise you can just ignore that

mossy snow
hasty blaze
simple egret
#

Okay, so close Unity and delete the Library/ folder. Then restart Unity and it'll get regenerated

soft hare
#

and i dont know why it doesnt create

hasty blaze
#

I added and deleted a few fonts with font asset crator and then it happened

simple egret
soft hare
#

it said it was created wheni debug logged its location

#

but i cant find it on exploroe

mossy snow
#

are there any exceptions in your console window when you try to create the file?

soft hare
#

no

#

i cant find app data in my user name

simple egret
#

There are handy methods like File.Exists and Directory.Exists, try them out

#

They return a bool whether the file or directory exists at the specified path

drifting fog
#

How do i get all game objects inside SubScene on unity editor?

lucid valley
#

e.g

 var scene = SceneManager.GetActiveScene();
 var rootObjects = scene.GetRootGameObjects();

And so change that scene to your subscene somehow. Have a reference to it somewhere

soft hare
#

i use them ill send you my code

simple egret
# soft hare https://gdl.space/uvubuzekiv.cs

Okay first things first, you should be using Path.Combine to combine paths. Using string concatenation can fail if you're missing (or having too much) path separators at the beginning/end of the paths

#

Second thing, Log the paths before you try to open a StreamReader/Writer to them

drifting fog
simple egret
#

Almost forgot, last thing. Change your AES key and IV, you just leaked them to everyone here

soft hare
#

okay

simple egret
#

Since you encrypt the payload, simple JSON serialization will do

soft hare
#

i used to use json

#

let me show you the code

soft hare
simple egret
#

As you wish

soft hare
#

use*

#

is there a way to save strings in json

#

i saw lots but they didnt work for me

simple egret
#

It's built-in feature yes

soft hare
#

how?

simple egret
#

Save a class instance that has string variables in it, and they'll be in the JSON

soft hare
#

???

#

can you show me an example

simple egret
#
class Sample
{
    public string Value;
}

Sample s = new() { Value = "hello" };
string json = JsonUtility.ToJson(s);
#

(produces)

{"Value":"hello"}
soft hare
#

i think i implemented it correctly

#

|| public static void SavePlayer(PlayerData data)
{
var saveTo = backUpCount == 4 ? savePathBackUP : savePath;
using (StreamWriter writer = new StreamWriter(Application.persistentDataPath + saveTo))
{
string json = JsonUtility.ToJson(data);
ConvertStringToBase64(writer, json);
writer.Close();
}

    backUpCount = (backUpCount + 1) % 5;
}||
simple egret
#

Yeah that side looks good

#

No need to call .Close() though the using statement takes care of it for you

soft hare
#

ok

soft hare
#

i am saving strings because they have codes

#

and i am putting in no codes if you unlocked non but when you unlock on close the game open it again the text says no codes

pure sapphire
#

Hi, does anyone know why I cant get my player to dash? I am trying to make an ability system using scriptable objects and for some reason (when i press space) the player wont dash at all. I have put debug.log at each case and they are showing in the console just fine so i think i have somehow messed up adding the velocity to the ridgidbody.

Ability: https://gdl.space/adevufetac.cs
AbilityHolder: https://gdl.space/dirumifixu.cs
DashAbility: https://gdl.space/upidajufoy.cs

simple egret
soft hare
#

i mean like codes like game codes like " for like ps4 0752ujfgsng89f"

simple egret
#

Activation codes?

soft hare
#

yep

#

but for my game

earnest gazelle
#

In my mind, DisallowMultipleComponent should be default :/
99.99% of components assigned to gameobjects are single

soft hare
#

i want them to be able to see activation codes they unlocked for my game

soft hare
#

in a text but the text doesnt activate a code ill show you my idle game code

earnest gazelle
potent sleet
#

thas dum

soft hare
soft hare
earnest gazelle
agile ice
earnest gazelle
#

I never ever have more than one specific component in a go

pure sapphire
potent sleet
#

why should I make multiple gameobjects

earnest gazelle
#

I put them separately in different children or create a controller class with array field

soft hare
#

spr2

simple egret
# soft hare seee

Yep I see now. The code is a huge mess by the way
You need to save them to your save file, and load them back up for them to be persisted through play sessions.
Your class is marked as obsolete, not sure why

earnest gazelle
#

but even I agree, do you have 99.99% scripts like weapons?

soft hare
#

yea same

earnest gazelle
#

WTH 😃

#

OK, thanks

zinc parrot
#

Is there a way to get what particles have a light?

potent sleet
#

@earnest gazelle Everyone is different man but forcing that restriction would cause hours of annoyance

#

if anything Unity should bother making disabled domain reloading a thing and playmode tint color default

soft hare
#

spr2 how do i make it to check if any codes were unlocked and which cwertain one was ulnocked

earnest gazelle
potent sleet
#

again, it's preference. For me it's easier to find all weapons in 1 GO sometimes

earnest gazelle
#

but I guess you are exaggerating, even in your style, more codes should be single

#

OK

potent sleet
#

yes ofc

simple egret
earnest gazelle
#

So, DisallowMultipleComponent should be default

potent sleet
#

ok tell Unity then idk this is kinda pointless

pure sapphire
agile ice
drifting fog
#

on the new unity physics do static colliders slow don`t ? (if physics is stateless, does it rebuilds everyf rame?)

soft hare
#

Assets\scripts\IdleTutorialGame.cs(191,25): error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'string'

#

Assets\scripts\IdleTutorialGame.cs(1080,35): error CS1503: Argument 1: cannot convert from 'method group' to 'string'

digital umbra
#

Does anyone have a code to move the character?

soft hare
#

i tried to use .tostring didnt work

simple egret
#
  1. You're trying to put a list of strings into a single string
  2. You're trying to put a function in a string
soft hare
#

1.?

simple egret
#

Literally what it says. You cannot put a List<string> into a string

#

How about you tell us what you're trying to do instead?

soft hare
#

text is a string?

potent sleet
simple egret
#

Yes precisely

soft hare
#

oh how should i put all the codes int the text ?

simple egret
#

You will have to loop through the list and add each item to the text

potent sleet
potent sleet
#

seperate by comma or /n

#

are you putting this into a file or something ?

soft hare
#

i know i have yo us Loop(){}

potent sleet
soft hare
#

use*

simple egret
#

You can Google it tbh

soft hare
#

how would that for mat

potent sleet
#

you wanna do unlock codes you should be learning how to work with strings, including looping them and whatnot

#

strings are just arrays of chars awkwardsweat

simple egret
#

Lists and other collections altogether - I saw things in their code that would make people want to alt-f4 themselves

digital umbra
#

look hey

simple egret
potent sleet
#

holy balls

rain minnow
pure sapphire
agile ice
#

sure

pure sapphire
normal arch
#

so i have some scripts for jumping in a topdown game

#

if the player jumos, their height level is raised and all colliders on that height level are disabled

agile ice
normal arch
#

however, this means that enemies can't walk through these disabled colliders, and i cant turn off the collider on the player because they still need to collide with things on higher platforms

#

is there a way i can fix this?

pure sapphire
#

but i guess it may be better to use the action map instead

agile ice
#

yea use action maps

pure sapphire
swift falcon
#

i have this condition system of a bonus only applying when certain conditions are met, or being multiplied by the number of conditions met
my problem is the amount of conditions i need to check for will keep rising as i add more types of conditions, i feel like the level of complexity is more than it can be

so my question is what are some ways to deal with this?

#

here's the code where i check the conditions, you don't need to read all of it or anything it's just to give you an idea

int ConditionsMet(SpecialEffect effect)
{
    List<Cell> cells = conditionsDict[effect];
    int conditionsMet = 0;
    int plants = 0;
    int empty = 0;
    int specials = 0;

    for (int i = 0; i < cells.Count; i++)
    {
        if (cells[i].HasPlant())
        {
            plants++;
            specials += cells[i].plant.plantData.seed.specialCount;
        }
        if (!cells[i].data.space && !cells[i].HasPlant())
            empty++;
    }

    EffectCondition effectCondition = effect.effectCondition;

    if (effectCondition.conditionType == EffectCondition.ConditionType.empty)
        conditionsMet += empty;

    if (effectCondition.conditionType == EffectCondition.ConditionType.hasPlant)
        conditionsMet += plants;

    if (effectCondition.conditionType == EffectCondition.ConditionType.specialCountEachPlant)
        conditionsMet = specials / plants;

    if (effectCondition.conditionType == EffectCondition.ConditionType.specialCountTotal)
        conditionsMet = specials;

    if (effectCondition.conditionCountingType == EffectCondition.ConditionCountingType.all)
    {
        if (conditionsMet == 0)
            return 0;
        else if (effectCondition.secondaryCountRequired)
        {
            if (conditionsMet >= effectCondition.secondaryCountReq)
                return 1;
            else return 0;
        }
        else if (conditionsMet == cells.Count)
            return 1;
    }

    if (effectCondition.conditionCountingType == EffectCondition.ConditionCountingType.per)
        return conditionsMet;

    return 1;
}```
digital umbra
#

but this is giving me 5000000 errors

swift falcon
#

you need to show the code not just the error

#

you seem pretty new i'd recommend looking up how to get references to things

digital umbra
swift falcon
#

you're adding the controller instead of getting a reference to it

#

use .GetComponent

digital umbra
simple egret
#

You need to use GetComponent as said earlier

#

You're still trying to use AddComponent here, which results in the very first log message

#

Cannot add component XYZ because it is already added

delicate olive
simple egret
digital umbra
#

they have no other easy

#

of code

simple egret
#

I was redirecting someone else

#

They deleted their message

digital umbra
#

uh?

simple egret
#

Forget it

#

Ignore me, I probably misunderstood what you were saying

digital umbra
#

a, I say that if they do not have another code to move the character but that is not that

vagrant notch
#

When you are using crossfade, how do you check the current time of the target animation?
Checking the clip time seems to check the time of the previous clip if it is at the start of the crossfade.

simple egret
digital umbra
#

that's what i was doing for a while

vagrant notch
#

Pretty sure he's asking if there are other methods of moving characters that is easier.

simple egret
#

Maybe, maybe not

#

Get another translator, because the one you used is not very performant

vagrant notch
#

I'm assuming he just needs to do some tutorials. None of the methods are easy if people don't understand the basics of unity and coding.

simple egret
#

Agreed on that point

simple egret
#

Looks good. Though I meant you should put your own questions (in Spanish) so they're translated in English, then you post the English here

digital umbra
woven dust
#

Been trying to fix this for hours anyone got any ideas?

simple egret
woven dust
#

It works in the context menu but not when I assign the same function to a button

#

Is there a way to check where they are?

digital umbra
simple egret
woven dust
#

Theres only one there and it also only has one attached

digital umbra
#

No wonder I get those 500,000 errors

simple egret
swift falcon
#

or at least some way of managing it a bit better

woven dust
#

It says true @simple egret

simple egret
#

Alright, one edit to that log, put gameObject as the second argument. Clear the console, play the game. Once you get the log, pause, click the log. It'll highlight the object that sent it

woven dust
#

Says false and nothing is getting highlighted

simple egret
#

From there check its Inspector, and the presence of the playerOne in the script slot

#

Well it said true beforehand

woven dust
#

Yeah...

simple egret
#

It can't magically change unless you changed something

woven dust
#

Probably because I clicked the button

#

Changed it back. it was because I pressed the button my bad

#

False to start with true after button is pressed

simple egret
#

Make sure you have the log as Debug.Log(playerOne == null, gameObject)

woven dust
#

ahhhhh

#

It highlights the object it should be on

#

and when I actually press the button and click the true one it does nothing

#

Running it from context menu give false again too

simple egret
#

The error is thrown on the line where you create the playerCounterArray array right?

#

Also not sure if it's a good idea to name a context menu handler as Start, which Unity will recognize as game start message

woven dust
#

Yeah I can get rid of it now it was to make sure it moved now im trying to feed in multiple players

#

and the ui

#

But the error is where I try to change the localPosition

simple egret
#

Yeah, attempt to change the position on something that's not assigned (null)

vagrant notch
#

Hate to barrage you with questions @simple egret ,
but do you know how handle the problem where GetCurrentAnimatorStateInfo(0) is reading the time of the previous animation rather than the one being blended in?

simple egret
#

Never dealt with context menu handlers though, so I don't know if there are some quirks with them
Same thing for reading animator info from the code

soft hare
#

hey guys so i did the for loop n my own

#

it worked but i have another question

vagrant notch
#

It's weird, all sources seem to indicate that it should read the new animation, but it definitely isn't.

soft hare
#

i am using googles ads/ admob

#

and it works fine

#

but whenever i refresh the code / save it while the code is running i get this

woven dust
#

How would I go about that?

#

If its not assigned it doesnt have transform.localposition

#

or just remove it from inspector

simple egret
#

Don't execute the code if it's null? Not sure, I don't have the context of the question

#

Is it even doing it while running the game, or just a pure Editor issue?

woven dust
#

The game runs and will actually work normally if I use context menu but the UI doesnt trigger it

soft hare
simple egret
#

Not sure why you're replying to me

soft hare
#

ill send you my code

#

just to get your attention

simple egret
#

It doesn't work like that here

soft hare
simple egret
#

You can't just request someone to work on your problem

#

Helpers can choose to chip in, but not the inverse

woven dust
#

Ive tried using a single variable to store the game object in too

#

But before I'd even setup the second if(currentPlayerTurn == 2) the first one threw the same error

#

So it doesnt look like its the array

soft hare
#

i under stand that very well btw but when i mean to grab your attention i mean to see if you want to help me or not

simple egret
woven dust
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class board : MonoBehaviour
{
    public dice dice;
    public turns turns;
    public UIScript uiScript;

    public GameObject playerOne;
    public GameObject playerTwo;
    public GameObject playerThree;
    public GameObject playerFour;
    public TextAsset positionsJSON;
    Collider2D infoTrigger;

    [System.Serializable]public class PositionInfo
    {
        public string name;
        public string type;
        public int rent;
        public int price;
        public int housePrice;
        public int rentOneHouse;
        public int rentTwoHouse;
        public int rentThreeHouse;
        public int rentFourHouse;
        public int rentHotel;
        public bool isOwned;
        public int owner;
        public int tileXPos;
        public int tileYPos;
    }

    [System.Serializable]public class PositionList
    {
        public PositionInfo[] position;
    }

    public PositionList positionList = new PositionList();

     public void Start()
    {
        Debug.Log(playerOne == null, gameObject);
        GameObject[] playerCounterArray = new GameObject[] {playerOne,playerTwo,playerThree,playerFour};
        positionList = JsonUtility.FromJson<PositionList>(positionsJSON.text);

        turns.playerPositions[0] = Random.Range(0,40);

        playerCounterArray[turns.currentPlayerForArrays].transform.localPosition = new Vector2(positionList.position[turns.playerPositions[0]].tileXPos,positionList.position[turns.playerPositions[0]].tileYPos);
        
    }
}
#

Im trying to change the location of a game object to a position saved in the JSON file

#

I did move it to a different function too

#

But this was a few hours ago so I dont have the code

#

I tried stripping it back to the last thing that worked

#

Which was just the random tile 1-40

#

I tried linking it to multiple game objects for the players but then it broke

simple egret
#

The error states that playerOne was not assigned in the Inspector at the moment this piece of code ran

soft hare
digital umbra
#

THAT THIS????!!!!!!!

woven dust
#

I also tried using GameObject.Find before that code ran

#

I'll try it again

simple egret
soft hare
#

spr2

gray thunder
#

Probably renamed it

soft hare
#

NullReferenceException: Object reference not set to an instance of an object
AdScript.Update () (at Assets/scripts/AdScript.cs:36)

quartz folio
#

rewardedAd is null

soft hare
#

it makes no sense because is loaded is a function

#

look at the code and you will understand why it makes no sense

quartz folio
#

Perhaps you have changed the code since that error and it's off by one, and watchAd is null. Either way, do some debugging

digital umbra
quartz folio
soft hare
soft hare
simple egret
#

Pay attention, Discord shows who you're replying to

soft hare
#

i know

simple egret
#

Then don't ping them

copper torrent
#

Anyone got any idea what is going wrong here? Using UI Toolkit

        VisualElement root = rootVisualElement;
        var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Resources/UI      Documents/LocalisationEditorWindow.uxml");
        VisualElement tree = visualTree.Instantiate();
        root.Add(tree);
        keyList = root.Q<ListView>("KeyList");

My keyList ListView element returns a nullreference even though I have an element in my tree that is named "KeyList" and is a ListView

soft hare
#

when i said yep i meant it toel

quartz folio
#

also, is this an editor script?

copper torrent
quartz folio
#

If you're making an EditorWindow it's often way easier to load assets by serializing them into the script itself

#

so you don't have to use AssetDatabase functions

copper torrent
#

This is my UI Builder tree. You can see here that I have a "KeyList" element. I can reference ANY element except ListView elements

#

And KeyList is definitely a ListView

soft hare
#

can some one help me with this NullReferenceException: Object reference not set to an instance of an object
AdScript.Update () (at Assets/scripts/AdScript.cs:36)

copper torrent
soft hare
#

rewarded ad is coming from a script google made

copper torrent
#

Google made it?

#

Try understanding the code you are using

#

When does rewardedAd get assigned a value?

soft hare
#

yep google leads

woven dust
#

@simple egret Cheers managed to sort it now

copper torrent
quartz folio
soft hare
#

NullReferenceException: Object reference not set to an instance of an object
AdScript.Update () (at Assets/scripts/AdScript.cs:36)

quartz folio
#

This doesn't point to any of your code

#

so I'm not sure why you think if cannot find the list view?

copper torrent
#

Because if I remove the

keyList = root.Q<ListView>("KeyList");

line, then it works

soft hare
#

@quartz folio are you willing to help me???

outer apex
#

can anyone help me conceptualize an algorithm?

I have a terrain that goes from 0,0 to x,y and a water plane I'm making a shader for. There's vertex displacement meant to simulate waves. Right now, I have the shader split its direction depending on the x,y coordinates, but I'm having a hard time completing the thought. So to split the waves so far I have the obvious, if x>y aim up and down, and if y>x aim side to side. This works up until we cross into the far corner of the terrain. But how do I get the last two quadrants of the terrain?

copper torrent
soft hare
#

to help it is not set to null at all

quartz folio
soft hare
#

anywere

quartz folio
copper torrent
#

Yeah, on the newest 2021 LTS. Dammit I was hoping it wasn't a bug

copper torrent
#

Can you make a new UI with the UI Builder, add a ListView, load it into an editor and click where the ListView is supposed to be?
I just did that
And it gives me the same error

noble leaf
#

Good night everybody

quartz folio
noble leaf
#

I am creating a tag game for my portfolio which is multiplayer using Mirror.
Now I am in the process of creating a character color swap using their tags for it. But with my current code, this swap only happens once. Can someone help me?

#

code

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

public class PiquePequeSystemTag : NetworkBehaviour
{
    private Rigidbody rb;

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

    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            other.gameObject.tag = "Caught";
            gameObject.tag = "Player";

            Vector3 repulsionDirection = transform.position - other.transform.position;
            rb.AddForce(repulsionDirection.normalized * 10f, ForceMode.Impulse);
            
        } else if(other.gameObject.CompareTag("Caught"))
        {
            other.gameObject.tag = "Player";
            gameObject.tag = "Caught";

            Vector3 repulsionDirection = transform.position - other.transform.position;
            rb.AddForce(repulsionDirection.normalized * 10f, ForceMode.Impulse);
        }
    }
}
copper torrent
quartz folio
idle crow
#

Is there a more performant way to GetComponent at runtime without having a referance to it prior?

quartz folio
quartz folio
#

The issue also might be that both objects have this script, so they will both try to swap

noble leaf
digital umbra
#

what just happened here

dusk plover
#

Would anyone happen to have a tutorial/reference to adding a noise map for some sort of underground ore spawning type thing

rain minnow
# digital umbra ?

This is a #💻┃code-beginner issue. Please move to that channel for beginner help. If you're following a tutorial, look at and compare their code. you spelled the type incorrectly. Also, you need to configure your IDE . . .

rain minnow
tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

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

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

cosmic rain
digital umbra
#

If you can help me with my code, I don't know what's happening, look

rain minnow
digital umbra
rain minnow
rain minnow
tight ice
#

this isn't a code question but can BoxCasts detect collisions if they originate from within a collider? regular raycasts can't so that's why i ask

digital umbra
#

what can I put there

#

@rain minnow

digital umbra
#

what can I put there

rain minnow
# digital umbra what can I put there

i mentioned it in my first message, you spelled the type incorrectly. spell it properly. look or google the type to see it from the unity docs. capitalization is important. again, you need to configure your IDE, it's a rule in order to get proper help in the server. it would easily point out this error to you and suggest how to fix it . . .

rain minnow
#

it's the program you're using to code . . .

rain minnow
tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

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

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

tiny delta
#

Anyone got any recommendations for making a system for shooting projectiles from a large variety of choices (I've got 10 or so planned but eventually I am going to add many more)? I'm considering the following, though I will also take any suggestions for new concepts or adjustments:

  1. Writing scripts attatched to prefabs to make complex projectile prefabs, then inputting them into an array or dict or similar for instantiation from the projectile creating GameObject (and maybe using a Class with projectile data on the projectile creator)

  2. Do something with ScriptableObject (which I don't understand too well just yet but I can definitely learn) to use very simple prefabs with everything run from the ScriptableObject.

#

I'm currently leaning towards the first option, but I also don't want to mess anything up for myself in the future

earnest epoch
# tiny delta Anyone got any recommendations for making a system for shooting projectiles from...

Both of these options would work well, the difference is really in where you're storing your data. The real difference here is that in the first case, you're using gameobjects + attached components as the part that you swap around. In the second, your ScriptableObjects would be more akin to a generic C# object and would need to be served to a component somewhere that does the shooting for all your cases.

#

I would personally lean towards the second option that it's likely a tighter fit for your use case, but the first method might be easier to get working if you are comfortable using prefabs to separate your different projectile/weapon setups.

tiny delta
#

Makes sense. I would be able to put an Update in a ScriptableObject for the projectile's movement, correct?

earnest epoch
tiny delta
#

Ah. How would I get the ScriptableObject to do the logic for a projectile then?

earnest epoch
#

So, ultimately the shooting would come from some sort of component attached to a GameObject. This would be true no matter what your approach.

tiny delta
#

Ah, makes sense

earnest epoch
#

If you use ScriptableObjects, lets call them ScriptableProjectile, you would need your shooting script to reference the ScriptableProjectile, read whatever so concerns it and then do the shooting.

#

You could have your shooter component call ScriptableProjectile.MyCustomUpdate() on it's own Update if you wanted to, but ScriptableObjects aren't components of GameObjects so they don't receive UnityMessages.

tiny delta
#

That makes sense. How do I make it so there are multiple instances of a single ScriptableObject so I can use multiple projectiles?

earnest epoch
tiny delta
#

I should clarify, I don't mean for each individual projectile type - I mean if I want multiple of the same projectile on screen at once

earnest epoch
tiny delta
#

I see, so I would use it like new myProjectile();

#

And would I use an array filled with ScriptableObjects or classes containing those objects to let my projectile creator access them?

earnest epoch
#
  public ScriptableProjectileData scriptableProjectile;
  public Awake() {
    Debug.Log(scriptableProjectile.weaponName);
  }
}

[CreateAssetMenu(menuName = "My Game/Scriptable Projectile")]
class ScriptableProjectileData : ScriptableObject {
  public string weaponName = "Shootyboi";
}```
In this example, you can drag the ScriptableProjectileData instance from your project folder straight onto the component MyProjectileBehaviour to attach it, but you would likely want to handle that programmatically in practice. @tiny delta
tiny delta
#

I think this all makes sense now, thank you

earnest epoch
# tiny delta I think this all makes sense now, thank you

My pleasure! Inevitably, your in-game components would have to be made a bit smarter to generate different appearances, velocities etc. depending on the data contained in the ScriptableObject, but this is a better way to go if you want to manage piles of different projectile loadouts later in development.

tiny delta
#

That makes sense, I plan on making a lot of projectiles (in my game you play as a wizard and you have a "spellbook" to cast from) so I really want to make sure everything works well for the future.

earnest epoch
#

@tiny delta [CreateAssetMenu()] correlates to how your script will be listed in this menu, accessible by right-click in the Project window.

tiny delta
#

Is there any way to have the Inspector require an array-style input in groups of 3, so that I can have the Prefab, ScriptableObject, and ProejctileName all visually linked together?

earnest epoch
tiny delta
#

oh right

#

And then I assume I could use the ScriptableObject's name for each projectile's name

earnest epoch
#

ScriptableProjectile.prefab, ScriptableObject.Name, etc. yeah.

tiny delta
#

gotcha, thanks! you're the best Omi

earnest epoch
#

It might be good practice not to use string name on your ScriptableObject, as that's reserved by UnityEngine.Object, though in practice it actually probably wouldn't matter.

swift falcon
#

Hey guys, I am curious how Bolt in Unity compares to visual scripting in Unreal?

swift falcon
#

Thank you!! @leaden ice

agile torrent
#

following a tutorial on making grids and it's asking for a return type on line 11

#

i'm not sure what im doing wrong though

earnest epoch
#

Use this signature: public void Grid(int width, int height)

agile torrent
#

so I write void before the method?

#

oh ok

earnest epoch
#

This looks like you're trying to make a constructor though. In that case, you would omit void and your method must have the exact same name of the class.

#

But it also wouldn't inherit from MonoBehaviour...

#

Is this supposed to be a constructor called as Grid grid = new Grid(myWidth, myHeight);?

agile torrent
#

I'm following a tutorial and I was following the steps this is what was in it but the thing is the guy doesn't explain anything in the code 😢

#

I've just done stuff on python and C this is first time working with OOP language so I'm still figuring stuff out sorry if it's a dumb question 😅

earnest epoch
#

Okay, so that's a generic C# class without any specific Unity implementation. Note they don't inherit from MonoBehaviour and the class name and method name are the same.

#

In Unity, you don't own the constructor for any MonoBehaviour, rather you factory those using GameObject.Instantiate<>(), but that's probably for another time. This is just a raw C# object. Know that you can't inherit from MonoBehaviour and that constructors must use the exact class name for the method. Correct those things and you should be back on track. @agile torrent

agile torrent
#

alright

#

I didn't notice the monobehavior tag next to my main class

earnest epoch
#

You wouldn't have known that new ClassDerivedFromMonoBehaviour(); is illegal.

agile torrent
#

so I can't make new classes if they're using monobehavior?

earnest epoch
leaden ice
agile torrent
#

the monobehavior thing is done by default when I make a new script in unity

#

i dind't notice

soft shard
tawny elkBOT
#
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)

nimble kernel
#

Does Unity shuriken particle system component not have a return event for when a burst is emit? I can't use VFXG because making example scene for unity store asset and don't want dependencies for the examples to work.

earnest epoch
nimble kernel
#

Thanks for checking that. That sucks. Wasn't planning to have to spend time coding for an audio asset. Brr

earnest epoch
nimble kernel
#

Indeed. However there's no real reason why that value couldn't have been exposed, and it should have been. I just can't use VFXG because it will require a user to DL that package before being able to see the example assets which I don't want

earnest epoch
vestal crest
#

hi, here i what i do when enter play mode i want to start from loading scene. for now it works perfect but i have an issue, when i use it like this if path is not wrong, always starts from loading scene

#

is there a way to make it depend on my choose? like menuitem or smth like this?

#

i still want it to work when press play button

earnest epoch
vestal crest
#

yes

earnest epoch
#

It would be nice to see the whole file such as if there is a larger class that EnterPlayMoveSceneChange belongs to.

vestal crest
#

thats the whole class

#

i want to start from loading scene when im in actually gamescene because i have things in loading scene dontdestroyonload

earnest epoch
#

How are you invoking this? There would have to be something that extends from MonoBehaviour referencing this class.

vestal crest
#

no

#

Initializeonload attiribute do that

#

everytime unity loads it works

earnest epoch
#

Ahh, right.

#

So, is your ultimate concern that you want to make sure certain resources are loaded no matter where which scene you are starting from in editor? @vestal crest

vestal crest
#

yes

earnest epoch
#

Or, do you want to be able to select the scene to load in the inspector?

vestal crest
#

but i want to be able to change it in editor too

#

i want to load const scene which is loading scene

#

but i want to be able to change it in editor if i would like to start from that scene or not

#

without editing script

#

like pressing some menu item or smth

earnest epoch
#

Right, so setting up the editor is the easy part. Where you have string loadingScenePath you can replace that with Scene loadingScene and in the inspector, drag the .scene file to the property in the inspector.

#

It becomes an object that can receive a reference to something in your project window.

vestal crest
#

actually thats not my problem

earnest epoch
#

Okay, did you want to select a scene from a dropdown menu?

vestal crest
#

i dont need to reference it

#

i want to start from loading scene for sure so path is constant thats okay

#

my problem is do i want to start from loading scene or not?

earnest epoch
#

Okay, so load from loading scene, then go back to wherever the editor was when you hit play?

vestal crest
#

i want to click a button to make a bool true which starts from loading scene

#

then i want to click another button to make a bool false which wont start from loading scene

#

ive tried this but i couldnt make it work

earnest epoch
#

Okay, that might be simple if I understand it correctly.

#

Please forgive me if I don't get this right.

vestal crest
#

no worries dude i appreciate your help thanks a lot

earnest epoch
#

So, create a public bool startFromLoadingScene or something like it on the MonoBehaviour that you want to have control this.

vestal crest
#

is there a no way doing this without monobehaviour

earnest epoch
#

You should be able to do whatever I mention on that class if it doesn't matter.

vestal crest
#

i think having a static constructor works before everything

#

i tried with dontdestroyonload on awake scene didnt even start

#

this script actually works before everything

earnest epoch
#

I'm actually not practiced in using [InitializeOnLoad]

vestal crest
#

A static constructor is always guaranteed to be called before any static function or instance of the class is used, but the InitializeOnLoad attribute ensures that it is called as the editor launches.

earnest epoch
#

That's fascinating; I haven't been in the habit of using that.

#

Anyway... EditorSceneManager.playModeStartScene. I think if you just don't set that, the editor should start playMode in the currently loaded scene. So, could you use a bool to prevent that line from being called?

vestal crest
#

i tried but how can i change that bool

earnest epoch
#

If you want this tied to the editor, you could create an EditorWindow that contains the button, like a custom toolbar in Unity.

#

If you want that button to not be tied to a MonoBehaviour but just live inside of Unity as an extension for your game, take a look at something like this: https://www.youtube.com/watch?v=491TSNwXTIg @vestal crest Please let me know if I'm missing the mark on what you want to achieve.

In this video we create a custom editor window to colorize objects!

● Project files: http://bit.ly/2t1w65j

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

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

♥ Donate: http://brackeys.com/donate/
♥ Subscribe: http://bit.ly/1kMekJV

● Website: http:...

▶ Play video
#

But the idea here is that the result of that window would produce a static bool that your [InitializeOnLoad] script would reference statically when playMode is run.

#

This is designing a custom window where you can create a button like a toolbar in the Unity Editor to be able to dictate state before you hit the play button.

vestal crest
#

i will try as soon as im available, currently i am working so it will take some time but i will make sure to tag you here when im done with it @earnest epoch

#

thanks a lot for your help

earnest epoch
# vestal crest i will try as soon as im available, currently i am working so it will take some ...

Thanks, I appreciate it! For inspiration, here is a way that I have handled making sure that scenes are loaded before my currently opened scene. https://pastebin.com/PadukXJi It's not elegant, but it does what I expect it to do.

dusky cosmos
#

I don't know if you know this video. Here the path is calculated only once. My game gives the player's position to the enemy every second and there is a delay because the number of enemies is high. How Can I Solve This? https://www.youtube.com/watch?v=G9Otw12OUvE

Let's see how many NavMesh Agents Unity can handle! That's right, another excuse for making a huge simulation ;)

♥ Support Brackeys on Patreon: http://patreon.com/brackeys/

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

♥ Donate: http://brackeys.com/donate/
♥ Subscribe: http://bit.ly/1kMekJV

● Website: h...

▶ Play video
open knot
#

How can I make my controller have acceleration when using GetInputRaw

deep fable
#

How do I stop recording? I pressed F10 (to do a screenshot with a custom program) and unity started recording, but I can't find the button to stop it

#

Unity docs say the recorder window should be there, but I can't see it

livid topaz
#

hey peeps, so ive been building a modular movement system and its now at the point where i can drop a movement style onto the player alongside the controller, is there at all a cleaner way i can do this, like for instance the controller having a dropdown that selects which style class i want to use

odd moss
#

anyone knows good CSG with boolean scripting api? probuilder 5.0.6 keeps pooping stack overflow when i try to cut holes for windows in wall via script (unity 2022.1.0b6)

livid topaz
#

guess its time now to add quake 1 and quake 3 movement

swift falcon
#

Someone knows umoderler for Unity?
Just wonder when you make a simple model and you enable convex on the meshcolider, why the mesh collision is not correct?

sharp juniper
#

I have a flower that you can shake and I want to add something if you shake all the flowers how can I make a way to check if all flowers have been shaken

#

So far thinking of changing their name and make a playerprefs with their names

stable rivet
#

if you want that to persist between sessions, you’ll have to include it in your save

sharp juniper
#

solved

marble panther
#

Does anyone know anything about generating a 2d dungeon? My plan is, ideally, to instantiate a bunch of prefabricated rooms and then make bridges between them on valid points

vestal geode
solid herald
#

I have this line of code: Instantiate(building1, new Vector2(buildingPos, hBuilding1), Quaternion.identity); that generates an object (building1) in some coords that are indicated with variables (builPos for x and hBuilding1 for y), but I want it to be a child of another object, how do i do it?

lucid valley
#

public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);

#

so just add it after the Quaternion.identity

solid herald
#

or i have to put it on "Transform"

lucid valley
stable rivet
# sharp juniper solved

PlayerPrefs is not designed to store progress data. It’s there to store, well, a player’s preferences. I would avoid relying on this to store every bit of persistent data you have in your game.

sharp juniper
#

Will use it for stuff like sounds etc. Cause later on I'm going to explore other saving methods when going to fix mu new game button so it deletes the save but leaves your settings alone

stable rivet
floral vale
#

How do I make it so a character which is just an image cause Unity2d moves to images and when the player spots them they stop

Im making a fnaf fangame on 2D so thats the reason

#

And I'm new to C#

#

Like it moves to different images

#

Ye

solemn latch
#

anyone know why i get JsonSerializationException: Self referencing loop detected for property 'normalized' with Type ' UnityEngine.Vector3.... ?