#archived-code-general
1 messages · Page 42 of 1
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
Do you think it would help if you could combine all the mesh reads into one GetData call? Or would that just end up allocating the same amount? It sounds like you want to be able to read all the mesh data in one frame, without having all the mesh data allocated at once.
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.
unfortunately I cant do that as some objects need to be seperate
the only part thats creating extra data is when I call getdata
Separate for what? What I mean is to allocate one big buffer (or one for vertices, one for triangles) that can fit all the meshes in the scene and use a compute shader to write each individual mesh data into individual sections of that buffer, skipping any attributes you don't need.
because they are split between different gameobjects
Perhaps this is what you are looking for https://docs.unity3d.com/2020.1/Documentation/ScriptReference/Mesh.MeshData.html
oooo? ill check it out!
This doesn't bypass the read/write flag.
It's just a more optimized API than the vertices and triangles arrays.
heck
https://docs.unity3d.com/2020.1/Documentation/ScriptReference/Mesh.AcquireReadOnlyMeshData.html
This method will throw an InvalidOperationException if isReadable is false for one or more input meshes.
damn ok
I didn’t know that was a requirement
I cant remember if this https://docs.unity3d.com/ScriptReference/Mesh.GetVertexBuffer.html
Required the read flag to be set
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?
it does not but unfortunately it requires the use of GetData, which will allocate memory that isnt freed until the next frame
Those SO's could still implement interfaces, you don't have to use one or the other
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?
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?
Will changing CharacterController.velocity actually move the character controller? Or does it only return the velocity the character controller is moving at
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
After applying your rotation, save it to a variable and then check at the beginning of the next frame if the rotation has changed.
but I cant do that because the script also modifies the rotation itself
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.
hmmmmm ok ill try that
trying to rotate a light tho
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)
Guys, in UGS, can we make a user create an account using custom email & address? I can't find it in authentication
Hey, how do I start a coroutine if a condition is met, and then it plays untill another condition is met?
You can put a while loop inside the coroutine and check your condition there
Remember to wait in the loop (like yield return null), otherwise it might freeze
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)
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)
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?
increase gravity, mass, or scale
if the oncollisionenter isn't firing when you want, make your collider bigger
none of these worked for me
If you move it directly with rb.MovePosition or rb.position it will likely not detect collisions
If you want physics responses you should move it with rb.AddForce or rb.velocity etc.
it does for me
pretty much instantly as well
i dont want to move it with script at all
i want it to be moved just by gravity
without the unwanted delay ofc
Hmm how are you noticing the delay?
You mean the collisions work normally but the OnCollisionEnter2D gets delayed?
i have the debug. log and ignorelayer lines, after collision object just kinda sits on the collider for a second before it starts actually ignoring that collision
Oh youre trying to ignore collisions when colliding?
from what i noticed collisions are detected properly just as long as they arent impacted by just gravity alone
I don't think it works very well. At the point when OnCollisionEnter is called, the collision has already happened.
yea
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
well it doesnt have to be that instant, as i said i moved the object with moveposition instead of gravity just for test and it detected the collision just as i wanted it to
its just that that when the object falls on the collider with gravity it takes it literal second to realise it collided
Yeah it probably stops completely and the rigidbody goes asleep or isn't updated until a certain interval
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
You could try to store the velocity (and angular velocity) and apply it back after the collision
basically its a revive buff system for my floppy bird
But is there a reason you don't ignore the collision beforehand?
You want the collision to happen?
yea but i suppose it would apply that velocity still with a 1 second delay
Oh you tried it already..?
when the bool isrevive is true i want the collision not to happen just as soon as the bird hits the pipe
then it starts a coroutine and the collisions are occuring again after 4 seconds
Can't you just set the bird's collider to trigger while isRevive is true?
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
Sounds like you want Physics2D.IgnoreLayerCollision()
i could technically make that work with ignoring layers as soon as the bool turns to true though ig
that is what im using
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
Because ignoring physics collisions does not notify the rigidbody that it is free to move again
It's just a little quirk in the engine but theres multiple ways to get around it
alright, that makes sense
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
but just simple debug.log message appears delayed
Is your console window docked or a separate window?
its next to project as per default
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?
Anyone prefer JB Rider over VC/VCS . does it support CoPilot?
That definitely looks like the UV map
cheers
That's a UV map that's for sure, but it looks baked. Somehow the warp adds additional texture detail to a distorted geometry. E.g. A UV projection from the geometry. How is this related to code? Ask this in #💻┃unity-talk
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"
Any non-blitable type actually
what makes a type non-blitable?
I suggest you start reading the manual https://docs.unity3d.com/Packages/com.unity.burst@1.8/manual/csharp-type-support.html
alright thanks
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)
{
...
...
...
}```
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
Ah Alright. Wdym first type btw? I can still add it even with that structure
Anyone knows if Screen.dpi is reliable on desktop computers, and on WebGL?
it might only be for classes or they may have finally updated it, but the MonoBehaviour would have to be the first type defined in that file. and of course by type i mean class, interface, struct, etc
the order of definition is not important
but the name is. it has to be the same name as the file
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?
ooh just discovered smooth damp!
Hey guys. How can I change a layermask in code? Ive tried buildMask = LayerMask.NameToLayer("Ore"); but its not changing in the inspector.
Do you actually assign that value to the gameObject layer property?
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.
For some reason I get this error when I go in game
Yes it should. Try debugging all the places where you set it.
Do you have a main camera?
Does it have the main camera tag though?
Well, that just means that you have other bugs🤷♂️
having a main camera shouldn't cause bugs
Food for thought: https://docs.unity3d.com/ScriptReference/Camera-main.html
Im using photon and it destorys the main cam
ill fix it
If there is no enabled Camera component with the "MainCamera" tag, this property is null.
im aware
Never heard about photon destroying the main camera on it's own
no i make it destory the camera if !view is mine
And because of a tag 
ill work around it
guys what is wrong with my rigidbody?
It's floating I guess.
Unless that's what you want it to do
How do I fix its floating?
Find the cause and eliminate it.
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.
I disabled my moving script and the rigidbody behaves the same
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
Then it must be something else. Apply the same logic to find the cause. If needed, try removing components entirely as well. If all the components aside from rb are removed and the issue still persists, then it's probably an issue with the rb itself.
well I guess I have to program my physics myself
no, you really don't
If you can't get it done with already existing physics, are you sure you can program the whole physics system? 😄
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
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
If you create a circle object with just an rb and collider, does it act the same?
I did that with a square
Can you record a video?
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
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
Ah good to know
I don't remember if this is a package that I have added or a default package
First of all, this is very alarming:
I know
That is fine
since It is checking for the rigidbody
that I removed from Mario
dw about it
Fix the error and try again. It just ads unneeded variables to the situation.
are you looking at the console or the square?
Both
Next thing to do is take a screenshot of your project - physics2d tab and project - time tab
where do I find physics2D tab?
project settings - physics2D
Also now I removed and readded the rigidbody to Mario and the square behaves normally
The square behaves normally?
Then the issue is not with the rb
Share you movement controller code
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
!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.
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
For some reason my tilemap stops my player likes theres some weird collider
What are you actually asking? Those are just normal serialised variables, no need for a custom editor
If you are making a custom editor you can display any serialized variable using a PropertyField
Iam doing custom editor and saw that feature somewhere but cant find it now. Another way I found is GUI.enbaled = true/false;
How do i make it so no one can see the code of my unity games?
You can't
u cant obfuscate at all?
How can I modify a rect transform delta size of an object
blackBorders.sizeDelta = new Vector2(2025, 1139);
that code doesn't work btw ^
No matter how much you try to, if someone wants to read it, they will. There are many tools out there to do that.
Alrighty
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.
Dont say you mean binary formatter?
Yeah
Dont
why
Read the article
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
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
the problem is that players tends to send game state and settings files with other players over internet
So you mean the object that is most accurately in front of the player ignoring the distance right?
Highest value of Vector3.Dot(cube.forward, (ball.position - cube.position.normalized) is closest to being in front
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/
·····················································...
@supple wigeon given this information, you can just loop through the list and keep track of the highest value and the corresponding ball
I dont use linq myself so cant really be much of a help
@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..
@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
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 )
@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
Hi, how would you pull a GameObject to another GameObject? Kinda like a grappling hook where it pulls the player towards it.
you could try using the MovePosition() method that's built into the rigidbody component
yeah
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
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?
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
does the floor have a mesh renderer?
no
I think you need actually a SpriteRenderer in this case
I mean chage the MeshRenderer variable to SpriteRenderer, since you're doing 2d stuff
I use primitive colliders as much as I can, sometimes as separate children so they can be rotated. Sometimes theyre not enough so I use convex MeshColliders. Really just depends on how accurately you need the colliders to match the visuals.
okay thanks!
do i need to declare [SerializeField] SpriteRenderer floor; as private?
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?
No this doesn't make sense:
- it's wasteful in memory
- it prevents you from inheriting other classes
You can achieve this with static imports or making static functions which do this in the singleton class
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
Uh ok I see
Thanks
Okay thanks !!
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.
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)
I mean, technically you could do [HideInInspector] lol
Depends what you want to access the variable
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?
true
I mean if I had a bunch of things that had stats I might just make some kind of ICharacter class for simple games
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
So MainCharacter : ICharacter. MobEnemy : ICharacter
By that do you mean from Start() I should run something else (eg. a MatchStartSetup)?
My bad, I hadn't seen the second part of your message
thats becasue i edited it lol
Having a stat manager class for ONLY your character stats sounds unweildy somehow. But maybe your character stats are complicated enough to warrant it
also:
InitPlayer() is a shit name for a method, its meainless..
more like SetPlayerStatsToDefault() or SetPlayerStats(Stats.default)
Just make life hard for everyone
can some one helps me in code advanced
//Is for inital character stats (ICS)
private struct ICS() {
...
}
that would be amazing
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;
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?
can i get some help in advanced code
Probably Unity being weird. Happens a lot with materials for me. Needed to initialize everything properly or it freaks out
Until I hit something in the inspector and Unity corrects stuff
sharramon can you help me
Maybe if u shared the actual problem and asked the question
ok look my problem is quit complicated i want to show it to you using share screen in a vc
quite
yea maybe, ive restarted it a couple times and no luck so im not sure
look i have a problem in a binary save system code and i want get help
!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.
I don't speak english sorry
do you spwak spanish?
what do you speak arbaic
french
nice i know some french ill try
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
@soft hare Post you problem with full description. Do not pin people to your questions or cross-post
ok
i have a problem that i cant explain i create a directory for a binary save system but it cant find it
#854851968446365696 on how to ask questions properly
okay
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 !
Are you sure that's the correct line and not after edit?
so do i post the error its quite long
oh yeah I playtested again, now it says line 38 reference exception
Show the full error
uhh it's so reliant on other scripts so please be ready to use your brain
oh wait you meant to say that to me or Agent47?
Test objects on that line. Print out with debug and find out which are not assigned
okay thanks will do
i posted full errors
Did you try reading them first? Or looking up what they mean?
i know what they mean
@delicate olive Should not use Find methods as well. Create proper reference in the inspector and link it.
but i dont know what is causing them i am creating a directory file anyways
Then you'll know that object reference exists
DirectoryNotFoundException: Could not find a part of the path "C:\Users\HASSAN\AppData\LocalLow\KEll\idle\saves\SaveSystem.txt".
here is my code
!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.
Copy paste the path in your windows explorer
and see what it says
here
i tried it says it doesn't exists but i am not trying to access that place anyways
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
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
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?
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
Are you sure they're the only errors you have? Press the collapse button
Also just try fixing the other errors first, then at least you know 100% that they are not preventing the button logic running somehow
Yeah they're all coming from the enemy clones
I tried but don't know how to check if the player is null
it's just adding a null check before
like
if (playerObject != null)
{
}
okay but it gave me errors before for trying to check a null object for null
idk how to explain it lol
oh yeah that
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;
}
}
player != null
but wait I really need that player.position check to stay there
do I just nest if statements
what is position?
just a monobehaviour script you've made?
or is it some property to get the transform
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
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
alr
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
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
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)
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);
}
}
add a log in the RestartScene to check if it runs
okay
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)
yeah ik but I want to keep my style in my first project consistent so I've gone with that because I learned that first
Also the debug.log didn't run, as expected
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
show the inspector of the button script
will do brb
I'll ask chatgpt to see what it can give
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
oh that's smart, I'll playtest
Ou wow cool
does nothing ://
well at least it improved the performance by like 1kb
disabling all the other UIs (shopui, scoreboardui) also did nothing
humm
I'll try creating a new button at the same location to see what would happen
other button also doesn't work
if you set it up using the inspector does it work?
yeah I set it to be a top child of the highest "Canvas" object
i mean like using the OnClick on the button script in the inspector instead of subscribing in code
I'll try, but I don't think that would affect the thing
yeah, i can't see any obvious reason why it's not working currently
okay so it's not just me
do you have nested canvases?
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);
}
}
looks like you dragged the wrong script
you want the restart button script
oh yeah that class is a RestartButton
not respawn script
"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
hmm okay
on that Canvas do you have the Graphics Raycaster component?
open the event system inspector while hovering over the button. There’s a possibility that another ui element could be covering the button (could be like an empty text as an example)
ah true could be that
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
still did nothing
okay will try
Does it turn bright red when you hover over it?
it should give you a bunch of details like what ui you are hovering over, what you are clicking etc
also tried doing this but couldn't understand, can you elaborate a little
Then something prevents the events from reaching it. Like an object over it
do I turn on debug mode
make sure you are in play mode while doing it
yeah I was I believe
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
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
Yeah something is clearly in front of the button
I bet
what if I move it to some other ui like the shopui and see if it works there
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
tried that before
and also moving it up in the hierarchy did nothing
hmm, it works when in the shopUI
Yep so the shop UI is the one blocking it
but the canvas of the shopui is disabled (unless I press tab) so it can't be blocking it
Disabled how?
Canvas Group with alpha turned down to zero : the object is still there
eh I think somebody got it earlier, nested canvas without a GraphicRaycaster. Type "t:Canvas" in scene hierarchy search window
Yeah the object will still be there. Disable the whole GameObject, not some script
obj.SetActive(false);
ok lemme try
wait didn't I already try that before
disabling all UI's but nothing happening
I assume that enabled Canvas is UI/RespawnManager/Canvas. Look at it and confirm it has a GraphicRaycaster on it
xevil can you help
You need to repost if your question got buried. People that just got here have no idea of what you're talking abou
yep there it is
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
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
hmm. I may have found the root of the problem
"Blocks Raycasts = false"
on the shopui it was set to true, and when i set it to false, the shopui buttons also stopped working
uh i create a directory is the first thing i do
so lemme try with this button
Yes that's completely normal
Setting it to false just tells the event system to not detect anything, even if the objects are there
Yep now it works lol
Still not the preferred solution though, just disable the shop ui object
I thought it was to block raycasts so that no buttons could be pressed, that's why I set it to false
Yeah will do that on my script to avoid further complications
Anyways thanks for the help guys
what's that?
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
did you go and look at the created file at the exact path the error mentions?
it doesn't stop the game, it doesn't break it, it doesn't fix after restarting
Okay, so close Unity and delete the Library/ folder. Then restart Unity and it'll get regenerated
yea but i cant find it
and i dont know why it doesnt create
I added and deleted a few fonts with font asset crator and then it happened
Thanks! I will try.
Pretty sure passing a file path to create a directory will throw an error. Can you show your code?
are there any exceptions in your console window when you try to create the file?
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
How do i get all game objects inside SubScene on unity editor?
It worked thanks!
if you can get the scene reference you can do GetRootGameObjects()
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
i use them ill send you my code
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
Thank you, it works
And third thing, BinaryFormatter is insecure and should not be used for applications anymore. It has security vulnerabilities.
Almost forgot, last thing. Change your AES key and IV, you just leaked them to everyone here
okay
what should i use thin ?
then
Since you encrypt the payload, simple JSON serialization will do
i want to you binary because its saves strings because i have lots of string in my code
As you wish
It's built-in feature yes
how?
Save a class instance that has string variables in it, and they'll be in the JSON
class Sample
{
public string Value;
}
Sample s = new() { Value = "hello" };
string json = JsonUtility.ToJson(s);
(produces)
{"Value":"hello"}
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;
}||
look
Yeah that side looks good
No need to call .Close() though the using statement takes care of it for you
ok
i have one more question
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
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
Hm sorry I have some trouble understanding what you mean by "codes" here
i mean like codes like game codes like " for like ps4 0752ujfgsng89f"
Activation codes?
In my mind, DisallowMultipleComponent should be default :/
99.99% of components assigned to gameobjects are single
i want them to be able to see activation codes they unlocked for my game
hell no
in a text but the text doesnt activate a code ill show you my idle game code
hell, yes
thas dum
seee
You assign N>1 components to gameobjects in same child go?
What happens if u increase dash force and add some upward force too
I never ever have more than one specific component in a go
i tried increasing the dash force and nothing happened but I will trying adding some upwards force
sure I have a weapon of the same script that does different things based on values in inspector
why should I make multiple gameobjects
It is really messy in my mind
I put them separately in different children or create a controller class with array field
spr2
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
but even I agree, do you have 99.99% scripts like weapons?
yea same
ok ill try
Is there a way to get what particles have a light?
@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
spr2 how do i make it to check if any codes were unlocked and which cwertain one was ulnocked
I said, I create a controller with array but separate gos is better than multi components in one gameobject.
each to name them, debugging, etc. easy to add/remove
I cannot think I have 50 same components in a go
again, it's preference. For me it's easier to find all weapons in 1 GO sometimes
but I guess you are exaggerating, even in your style, more codes should be single
OK
yes ofc
You should put the codes you unlocked in a list. Then to see if it was unlocked just check if that list contains the code.
Save your list to the save file, so progress is persisted through game restarts
So, DisallowMultipleComponent should be default
ok tell Unity then idk this is kinda pointless
tysm
havent had any luck getting it working :/
i was thinking issue might be ur rigidbody mass, friction, drag properties making it hard to push ur rigidbody
on the new unity physics do static colliders slow don`t ? (if physics is stateless, does it rebuilds everyf rame?)
ineed some more help
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'
Does anyone have a code to move the character?
i tried to use .tostring didnt work
- You're trying to put a list of strings into a single string
- You're trying to put a function in a string
1.?
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?
Yes precisely
oh how should i put all the codes int the text ?
You will have to loop through the list and add each item to the text
foreach looop them then append them ?
thank you
how do i do that ? i forgot
i know i have yo us Loop(){}
foreach string code in unlockedcodes
use*
You can Google it tbh
how would that for mat
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 
Lists and other collections altogether - I saw things in their code that would make people want to alt-f4 themselves
You need to ask a question in order to get help about something
just saw the monolith
holy balls
No one knows what you're trying to ask. Post a relevant question. If it's not an intermediate or general coding question, move to #💻┃code-beginner. If it does not deal with coding, move to #💻┃unity-talk
ok. Would it help if I also show u the player controller and input provider script?
sure
PlayerController: https://gdl.space/icohawunat.cs
InputProvider: https://gdl.space/legupajico.cs
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
is Dash configured in your Input Action correctly
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?
well i shouldnt need to as I assigned a key to use in the dash in the AbilityHolder script
but i guess it may be better to use the action map instead
otherwise code looks fine to me
yea use action maps
ok thanks for the help i will try and use the action map
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;
}```
but this is giving me 5000000 errors
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
you're adding the controller instead of getting a reference to it
use .GetComponent
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
Lmao I have that exact same problem but with trying to add new enemies to my Wave System
Sir this is a code channel
=> #💻┃unity-talk
uh?
a, I say that if they do not have another code to move the character but that is not that
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.
I'm having a really hard time understanding what you mean. Try putting your sentences through a translator: https://deepl.com
that's what i was doing for a while
Pretty sure he's asking if there are other methods of moving characters that is easier.
Maybe, maybe not
Get another translator, because the one you used is not very performant
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.
Agreed on that point
😒 🤨
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
.
Been trying to fix this for hours anyone got any ideas?
You have another Board script attached somewhere else, and it's the one throwing that error
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?
that gives me the controller variable
Sure thing, in the Hierarchy search bar, t:Board
Theres only one there and it also only has one attached
No wonder I get those 500,000 errors
Alright, first line of that Start method log a Debug.Log(playerOne == null), it should say false
damn
lmk if you find a solution
or at least some way of managing it a bit better
It says true @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
Says false and nothing is getting highlighted
From there check its Inspector, and the presence of the playerOne in the script slot
Well it said true beforehand
Yeah...
It can't magically change unless you changed something
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
Make sure you have the log as Debug.Log(playerOne == null, gameObject)
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
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
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
Yeah, attempt to change the position on something that's not assigned (null)
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?
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
It's weird, all sources seem to indicate that it should read the new animation, but it definitely isn't.
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
How would I go about that?
If its not assigned it doesnt have transform.localposition
or just remove it from inspector
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?
The latter might be better asked in #↕️┃editor-extensions, maybe
The game runs and will actually work normally if I use context menu but the UI doesnt trigger it
NullReferenceException: Object reference not set to an instance of an object
AdScript.Update () (at Assets/scripts/AdScript.cs:36)
Not sure why you're replying to me
It doesn't work like that here
You can't just request someone to work on your problem
Helpers can choose to chip in, but not the inverse
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
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
Can you post some context here? Apart from the fact that you're trying to run some code in a context menu, I know nothing else of your code/game architecture
ie. what are you trying to do here?
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
The error states that playerOne was not assigned in the Inspector at the moment this piece of code ran
THAT THIS????!!!!!!!
Read the error message
you cant add the script because their is an error
spr2
Probably renamed it
NullReferenceException: Object reference not set to an instance of an object
AdScript.Update () (at Assets/scripts/AdScript.cs:36)
rewardedAd is null
it makes no sense because is loaded is a function
look at the code and you will understand why it makes no sense
Perhaps you have changed the code since that error and it's off by one, and watchAd is null. Either way, do some debugging
the name of the script and the code are spelled correctly
Show us
and yet there is a compiler error
its not the name
They were not replying to you
Pay attention, Discord shows who you're replying to
i know
Then don't ping them
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
when i said yep i meant it toel
either that's not true, or the error is not pointing to what you say it is
also, is this an editor script?
Yes it is
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
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
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)
rewardedAd must be null then. Try doing print(rewardedAd) beforehand
Google made it?
Try understanding the code you are using
When does rewardedAd get assigned a value?
yep google leads
@simple egret Cheers managed to sort it now
Yeah, just trying out UI Toolkit for now. Any ideas on what might be going awry here? I just don't understand why I can't reference ListView elements but I can reference any other type of element easily
can you show the stack trace of the error
NullReferenceException: Object reference not set to an instance of an object
AdScript.Update () (at Assets/scripts/AdScript.cs:36)
This doesn't point to any of your code
so I'm not sure why you think if cannot find the list view?
Because if I remove the
keyList = root.Q<ListView>("KeyList");
line, then it works
@quartz folio are you willing to help me???
.
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?
It's probably not my code. (the hubris)
But rather how the UI Builder works itself. I'm just a bit stumped. Sorry about that - started using UI Toolkit a few days ago so I might not have the hang of it yet.
It's probably some UIToolkit bug. If you're on a recent version of Unity and can get replication steps it's probably worth reporting
anywere
Well, something is null in that area, use the debugger and find out what it is
Yeah, on the newest 2021 LTS. Dammit I was hoping it wasn't a bug
Hey Vert, could you try something out for me?
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
Good night everybody
It seems fine in an Editor Window (I am using 2023.1)
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);
}
}
}
Thanks for trying! Might have to upgrade then
you need to use an else if. Your first if statement runs, changes the tag, which then causes the second to run
Ok ok
I will try this
Is there a more performant way to GetComponent at runtime without having a referance to it prior?
Not work
can you update the above code to show what you changed
I tried this
The issue also might be that both objects have this script, so they will both try to swap
Who is a prefab so yes
My player with asset mirror is a prefab in localserver
Would anyone happen to have a tutorial/reference to adding a noise map for some sort of underground ore spawning type thing
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 . . .
!ide
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.
I'm not sure there's a tutorial that specific. It would also depend a lot on other things and systems in your game.
If you can help me with my code, I don't know what's happening, look
i already answered what was wrong. you should use the #💻┃code-beginner channel, not the more advanced one for your issues . . .
I was wrong again
sorry
that's not where the error is at. you need to configure your IDE. the error you posted says line 9, that is not line 9 . . .
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
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 . . .
put what ide is that
it's the program you're using to code . . .
!ide
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.
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:
-
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)
-
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
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.
Makes sense. I would be able to put an Update in a ScriptableObject for the projectile's movement, correct?
Actually, no. That's behaviour that ScriptableObjects don't share with MonoBehaviours.
Ah. How would I get the ScriptableObject to do the logic for a projectile then?
So, ultimately the shooting would come from some sort of component attached to a GameObject. This would be true no matter what your approach.
Ah, makes sense
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.
That makes sense. How do I make it so there are multiple instances of a single ScriptableObject so I can use multiple projectiles?
The simplest way, and what I would recommend for you, is to create them on disk. An advantage of ScriptableObjects and where they shine here is that you can create them in the project view like materials, shaders, etc.
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
ScriptableObject is a class like any other, but wouldn't be a class for the object that appears on-screen. Your ScriptableObject is a model only. You would still need a prefab made from MonoBehaviours for the in-game part.
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?
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
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.
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.
@tiny delta [CreateAssetMenu()] correlates to how your script will be listed in this menu, accessible by right-click in the Project window.
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?
You could do that, but if I can take the liberty to make some assumptions, why don't you reference your prefab on your ScriptableObject?
oh right
And then I assume I could use the ScriptableObject's name for each projectile's name
ScriptableProjectile.prefab, ScriptableObject.Name, etc. yeah.
gotcha, thanks! you're the best Omi
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.
Hey guys, I am curious how Bolt in Unity compares to visual scripting in Unreal?
Thank you!! @leaden ice
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
Methods must provide return types if they aren't constructors. The "no return type" return type is void.
Use this signature: public void Grid(int width, int height)
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);?
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 😅
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
It's certainly not dumb. This is why I prefer that people learn C# before starting in Unity.
You wouldn't have known that new ClassDerivedFromMonoBehaviour(); is illegal.
so I can't make new classes if they're using monobehavior?
You can, but you have to use Unity's provided factory, which is GameObject.Instatiate() and not new directly.
You did two things wrong:
- You didn't use the same name for the class and the constructor
- you derived from Monobehaviour for no reason
the monobehavior thing is done by default when I make a new script in unity
i dind't notice
If you rename a script file after you created it, it will not automatically update the class name too, its possible to get mismatches that way
!vs
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)
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.
https://docs.unity3d.com/ScriptReference/ParticleSystem.html It doesn't appear to. You might have to wrap ParticleSystem.Emit in your own controller.
Thanks for checking that. That sucks. Wasn't planning to have to spend time coding for an audio asset. Brr
Goes to show why VFXG is the preferred solution...
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
I forget now, but if GPU instancing is a critical component of Shuriken, then it might be impossible to know when a burst was emit if it is owned by the GPU, but I am spitballing here.
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
It seems like you're forcing the game to play from a certain scene when you hit play, just to be clear.
yes
It would be nice to see the whole file such as if there is a larger class that EnterPlayMoveSceneChange belongs to.
thats the whole class
i want to start from loading scene when im in actually gamescene because i have things in loading scene dontdestroyonload
How are you invoking this? There would have to be something that extends from MonoBehaviour referencing this class.
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
yes
Or, do you want to be able to select the scene to load in the inspector?
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
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.
actually thats not my problem
Okay, did you want to select a scene from a dropdown menu?
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?
Okay, so load from loading scene, then go back to wherever the editor was when you hit play?
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
Okay, that might be simple if I understand it correctly.
Please forgive me if I don't get this right.
no worries dude i appreciate your help thanks a lot
So, create a public bool startFromLoadingScene or something like it on the MonoBehaviour that you want to have control this.
is there a no way doing this without monobehaviour
You possibly could, but I'm not familiar with whether your script has a place in the script execution order.
You should be able to do whatever I mention on that class if it doesn't matter.
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
I'm actually not practiced in using [InitializeOnLoad]
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.
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?
i tried but how can i change that bool
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:...
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.
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
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.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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...
How can I make my controller have acceleration when using GetInputRaw
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
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
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)
scratch that, i just figured that i could have a chain reaction of requirecomponent working from the style backwards to the controller and input manager
guess its time now to add quake 1 and quake 3 movement
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?
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
whenever a flower is shaken, add to a count somewhere. all flowers have been shaken when that == your total number of flowers
if you want that to persist between sessions, you’ll have to include it in your save
but how can I do it that you don't shake just one flower
solved
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
Sure there are countless different ways to do that and resources too
https://youtu.be/t1O0_yHe-6Y wave function collapse comes to mind as one
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?
i think the next parameter sets the parent
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
so just add it after the Quaternion.identity
in "parent" i have to put the name of the parent
or i have to put it on "Transform"
the transform of the parent
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.
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
whatever floats your boat 🛥