#archived-code-general
1 messages Β· Page 301 of 1
hmmm... so it's in a savable format. that's good! but how do I actually save it?
You can use a serializer like JsonUtility to save the data to a file.
What are you trying to do actually?
save all this data out to the scene
A save system? Or just apply changes during play mode?
I think maybe it's because I"m doing it at runtime
if I did this at editor time, would it save?
Depends on what you're actually doing.
or yes, apply changes during play mode
Well, you can copy the component values at play time and paste them after exiting the play mode.
You're not really supposed to edit the scene at runtime.
perhaps I need to make this thing an editor script, and that will populate this stuff at editor tie
time
and therefore be saved for play
but thank you, knowing you shouldn't edit the scene at runtime is helpful info indeed!
Yeah, you'd write an editor script if you want to populate the data.
When pressing ESCAPE, everything works. the PauseMenu opens, but on the buttons there is no hover effect and when i press leftclick my mouse disappears. can someone help?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour
{
public GameObject PausePanel;
// Update is called once per frame
void Update()
{
Pause();
}
public void Pause()
{
if(Input.GetKey(KeyCode.Escape))
{
PausePanel.SetActive(true);
Time.timeScale = 0;
}
}
public void Continue()
{
if(Input.GetKey(KeyCode.Escape) && PausePanel.activeSelf)
{
PausePanel.SetActive(false);
Time.timeScale = 1;
}
PausePanel.SetActive(false);
Time.timeScale = 1;
}
public void backToMainMenu()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);
}
}
you aren't actually unlocking the mouse cursor so when you click again it goes back to being locked. pressing escape only releases it in the editor
as for why you aren't getting hover effects, either it's because the time scale is preventing the UI from updating for whatever reason, or you don't have an event system in the scene oh wait this is totally caused by the mouse not being unlocked lol
you can ask in #π²βui-ux for help with your buttons
oh yeah you're right, just fixed that, ty π buttons are working now
Are there any alternatives to Unity.Mathematics.noise for generating terrain using Job System? Its painfully slow.
Why is my character controller floating? Actually pulling my hair out... None of my code is attached. Just using Unitys character controller atm.
charactercontroller and rigidbody do not mix. and you have to manually apply gravity to the CC
In the game I'm making, in the scene where the gameplay is, I have several AudioSource. The problem I have is that the first time the scene is loaded, coming from another one, it can be heard, but if I reload the scene, coming from another one, it can't be heard.
Does anyone know what could be happening? I can take screenshots if necessary.
but removing the rigidbody, the character no longere moves?
move with one or the other. do not put both on there
also you should really not be doing multiplayer if you aren't even familiar enough with the engine to move an object
I've been working in Unity professionally for 6 years now 
I've just not used Unitys character controller before.
yikess
yeah we have our own ways of handling movement etc so never had to use unity's character controller
You are a developer professionaly for 6 years and couldn't Google that you don't mix character controller with rigid body, got it
I'd like to know where these jobs are that hire people not very familiar with the most common issues people face in the engine
that's not so weird? the first 3 years of my career were entirely spent on games without any physics lol
if you ever find out, lmk pls
Well I googled wondering why my character controller was floating and not much came up about rb + cc not working together. Hence my next step was to come ask here.
Maybe if Unity was a decent engine it'd throw a warning if both of those are on the same gameobject as they're apparently incompatible.
yea - engine issue
It's more than just decent, otherwise it wouldn't be the most used engine on most game jams π
Obviously I'm exaggerating. But there's a lot of silly things that Unity just doesn't explain. This being one of them
i personally think the documentation is pretty clear that the RB and CC should be used on their own
imagine if they had put that in the engine though as a warning. Feels pretty silly not to.
becuase there are moments where you could techically use both
for example you use the CC for movement, and have a grapling hook that will make use of the RB, but you toggle the components between them
I have component of player and another component for jumping
First message is Player Start method
then Player Update
then Jump Update
and i get error becasue Jump Start has references
BUT this doesnt happens always. sometimes start of Jump is called right after Start of Player, why?
the order of execution for scripts are basically random
do not rely on specific ordering of component's Start and other messages. unless you specify an execution order it is not guaranteed. and if you find you have to modify the execution order a lot then you are designing your systems poorly
I never has this shit before, when player was in scene, now switched to instantiating him, and it happens 50% of time
there is no guarantee that the start for jump is called before the start of player
like i said, it basically random
unless like boxfriend said you specify a custom execution order which is not a good thing to do for scripts like that
I moved these references to Awake function
I know Start is random but Update? i though Update is always after start on same object
Update will always come after Start on the same object. but that doesn't mean one object's Start will happen before another object's Start and/or Update
Well object yeah, but components on same object?
yes components on the same object
I mean obviously not, but i thought otherwise
those are also ran in a random order
yeah you should use awake for initializing stuff most of the time
use Awake to initialize an object's own variables, use Start to reach out to other objects. This will ensure that variables are already initialized before other objects start trying to access them
Only talk to woke objects!!
I made some code for a camera object to zoom in if something enters its trigger zone. However, it also zooms in if it enters the triggerzone of another object, and I don't want that. How can I fix that? can I specify that in the OnTriggerStay method or...
nothing feels better than writing everything in 1 file then finishing it and separating it into multiple files
this was all like 3 files and 300-500 lines each
i do everything myself
its almost masochistic how much i detest using anyone elses tools unless i have to
i dont even use lookat i do it myself bruh
thanks!
yes but how many namespaces?!
is it fine practice to have a singleton monobehaviour that holds references to a bunch of scriptable objects? iβm making a weapon system where scriptable objects represent a weapon in the inventory but hold reference to prefabs that are the actual weapon themselves
Yes. Common even
oh hell yeah
good to know, thank you!
was worried that i was doing something stupid haha
what is the best way to check if a nav mesh agent has reached his destination cuz this isnt working
{
if (animator.runtimeAnimatorController != idle)
{
animator.runtimeAnimatorController = idle;
agent.isStopped = true;
Debug.Log("Agent has reached its destination.");
}
}```
whats a namespace
well
how would i use it in unity
-lua user
You don't, you use it in C#. It's an organizational thing.
ok can you give me an example
the closest you can get in Lua are modules but not really..
you can think of namespaces in c# are like "scope"
I'm making a settings system for my game using reflection. I get all the fields of the settings script on start:
Type settings = typeof(Essential.Settings);
FieldInfo[] info = settings.GetFields(BindingFlags.Public | BindingFlags.Instance);```
Then make UI out of them:
```cs
if (GetAttributes<Slider>(property))
{
Instantiate(slider, settingsView);
}```
which works perfectly and all, but I'm not sure on how I can create new settings out of them:
```cs
public void Apply()
{
var settings = new Essential.Settings()
{
// ..?
};
SaveManager.CreateSettings(settings);
}```
I essentially need to convert the UI back to fields, and I don't know how to do that in order to create a class
I also have this dictionary in case it ends up being useful:
```cs
public Dictionary<Transform, FieldInfo> settingsUI = new();```
That seems a bit overkill
Using Reflection, that is.
I essentially need to convert the UI back to fields, and I don't know how to do that in order to create a class
Surely you don't mean creating new fields, right?
You can get Collider info with OnTriggerStay, which can give you access to the object that collider is attached to, and things like layer, tag and scripts, you could use any one of those to differentiate your camera from the objects that should trigger the action, and if all of your triggers are on the same layer you can have them ignore the layer or ignore interaction between specific colliders with the Physics class
But as far as "converting the UI back to fields" you have to check to see if the input element has changed and then set the field value. You can use FieldInfo.SetValue https://learn.microsoft.com/en-us/dotnet/api/system.reflection.fieldinfo.setvalue?view=net-8.0
They were just being sarcastic.
No need to use them
I've been able to solve it quite easily, and I do feel stupid for not realizing this earlier.
I just specified the condition if(other.isTrigger == false)
Yeah, definitely but I do like things really modular
I mean, you could use a dictionary or list or something of structs
And no of course, I just want to set all the settings fields to their respective UI counterparts' values (not sure if this makes sense)
like rather than have 5 raw floats on the Settings class and using reflection to get them, have a struct like public struct MySetting { string fieldName; float value; } and then have a collection like a List<MySetting>
Yeah, but then i'd have to do more manual work
because now I can just add a field to this class and an attribute and everything but the logic works
camera jittering when rotating it with the player model at the same time any help as to why? Im pretty sure its the timing of how I rotate both but Im not sure how to fix it, I have tried multiple ways
void Update()
{
// Checks to see if player is touching ground layer
grounded = Physics.Raycast(transform.position, Vector3.down, height * 0.5f + 0.2f, ground);
MyInput();
DragControl();
SpeedControl();
Hotkeys();
}
private void FixedUpdate()
{
MovePlayer();
}
private void LateUpdate()
{
CameraMove();
}```
```cs
private void MovePlayer()
{
rb.MoveRotation(orientation.rotation);
if (grounded)
rb.AddForce(playerVelocity.normalized * currSpeed, ForceMode.Impulse);
else if (!grounded)
rb.AddForce(playerVelocity.normalized * currSpeed * airMultiplier, ForceMode.Impulse);
}
private void CameraMove()
{
float mouseX = Input.GetAxisRaw("Mouse X") * sensitivityX * Time.fixedDeltaTime;
float mouseY = Input.GetAxisRaw("Mouse Y") * sensitivityY * Time.fixedDeltaTime;
if (cameraPlayer != null)
{
rotationY += mouseX;
rotationX -= mouseY;
rotationX = Mathf.Clamp(rotationX, -70f, 70f);
cameraPos.rotation = Quaternion.Euler(rotationX, rotationY, 0f);
orientation.transform.rotation = Quaternion.Euler(0, rotationY, 0);
}
}
If you want to add more logic around how settings are grouped or add metadata to the fields (like min / max values for the sliders) a struct gives more control and flexibility
Can I apply a force on a rigidBody inside of the FixedUpdate function?
for some reason my code works when I put it in Update but fails to move my rigidbody at all when I use FixedUpdate.
void FixedUpdate()
{
if (!isLocalPlayer) return;
var moveX = Math.Clamp(movementJoystick.Horizontal, -1.0f, 1.0f);
var moveY = Math.Clamp(movementJoystick.Vertical, -1.0f, 1.0f);
var shootX = Math.Clamp(shootingJoystick.Horizontal, -1.0f, 1.0f);
var shootY = Math.Clamp(shootingJoystick.Vertical, -1.0f, 1.0f);
var move = new Vector3(moveX, 0.0f, moveY);
var shoot = new Vector3(shootX, 0.0f, shootY);
CommandUpdateMovementJoystick(moveX, moveY);
CommandUpdateShootingJoystick(shootX, shootY);
Debug.Log(move);
//Apply movement
if (move.magnitude > 0.1)
{
rb.AddForce(move * Acceleration);
}
//Clamp the velocity
if (rb.velocity.magnitude > MaxSpeed)
{
rb.velocity = Vector3.Normalize(rb.velocity) * MaxSpeed;
}
if (shoot.magnitude > 0.1)
{
}
}
When logging the move vector it indeed has a magnitude greater than 0.1
I get what you mean, but I'm also serializing this class as a json so I want to keep the data types as simple as possible
Hi guys,how can i solve this problem?
use Path.Combine and dont put a / in front of your file name
Yes, unfortunately Unity's JSON serializer implementation is really disappointing. It lacks a lot of really basic functionality / support for typical JSON features
Or just use PlayerPrefs?
Rather than direct File IO
You only need to bother with writing to files for larger data chunks (>2kb)
Thank you so much it works
Try to never use playerprefs
Files are much more versatile and easily handled on both sides (while running the game, and uninstalling)
Never?
Playerprefs are ALRIGHT (i guess) for things like game settings like volume and resolution
But even that I prefer files
If you only need to save a single value, like score, it would be fine. But may as well use files STILL imo
I would think something as simple as setint / getint would be preferable to having to write an int to a file and then read it back (way more code to write in the latter scenario)
It is about one or two extra lines, and it doesn't rely on brittle strings
And the amount of lines you have to write has never been of meaninful inportance to me except at extremes (20 lines vs 1). If writing 10 lines one time makes things easier down the line than the 1 line solution, I will always go for the 10 lines. Even the 20 lines
sure they are easier. but playerprefs writes to the registry on windows. do you really want to pollute the registry with your meaningless data that could just as easily be written somewhere sensible?
Yep, I think I've figured out the reflection method though, thanks!
My entire save system originally was 10 lines of actual code, and it can save any type I want
Yeah, honestly, playerprefs is gonna require more code unless you are only saving a COUPLE values
Each value needs at least two lines of code (get and set, assuming you only do that in one place each) So 5 values is already the same amount as bawsi's solution
Plus if you try to save anything else, you have to either convert or use a file anyways
Playerprefs only handles basic types
I am trying to do a simple mesh drawing using drawmeshnow (working with gizmos with materials) to make the 2d bounding box from a 3d (vertex defined) bounding box (not actual bounding box).
No matter what i do the shape will consistently be slightly offset and i cant figure out why
https://discussions.unity.com/t/drawing-a-screen-space-rectangle-with-graphics-drawmeshnow/12873 (closest thing to what i need i found)
the code isnt crazy its just a static shape
Then i use ```cs
Camera camera = SceneView.currentDrawingSceneView.camera;
//Translation using camera.WorldToScreenPoint
//Find Extremities like above
//Then using camera.ScreenToWorldPoint
Hi, I want to draw a screen space rect based on a unity rect. Currently I do this : Vector3[] vertices = new Vector3[4]; vertices[0] = new Vector3(testPos.xMin, testPos.yMin, Camera.current.nearClipPlane); vertices[1] = new Vector3(testPos.xMin, testPos.yMax, Camera.current.nearClipPlane); vertices[2] = new Vect...
I don't understand... if you do a file-based approach you have to write custom code for serializing and deserializing your data, no? I feel like I'm missing something
You have to write a single short method for serializing ANYTHING and a single short method for deserializing ANYTHING.
You only have to do it once. I have had the same save system across many projects
Each playerprefs system needs to be fairly bespoke though, meaning you will need to rewrite parts of it for each project
If you de/serialize with generics T then you would only need 1 generic function that takes in your data and the path of the file for serializing, and just the path for deserializing, you get a object back which you can cast to T, and T can be any data type you want, any serialized class or struct, for example, you could do something like Save(somePlayerStatsRef, somePath) or Load<PlayerStats>(somePath), being generic functions that handle de/serialziation respectively, be it JsonUtility, or more robust solutions like Newtonsoft JSON
I'm populating this data at Editor time, but on play it clears. It also clears when the scene is reloaded. Is there a way of getting this to stay around and get saved like any game object? I know I cam serialize to disc but it just seems like there should be a simpler way
Do you touch those variables in code?
I do! from an editor script
an editor... extension I think it's called?
oh you mean at runtime?
Well, just trying to see why it changes. Could be the editor script.
May as well show that
!code
π Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
The only way it could change is if some code is changing it, yes
I just checked and nothing is changing it, but it all clears out on play
the method is private and used in one place. a debug print shows this also
perhaps I need to mark it as dirty
EUREKA
we learned something here today. WHO KNOWS WHAT
Ohhh yeah. That may be it. Not sure.
You could try asking in #βοΈβeditor-extensions by the way. I don't do that very much, so you may find better help
but it worked
Oh dang, ignore that last message haha. Well, nice
thanks for the help though!
very useful to know it SHOULD have been working
this was the hardest thing about all this. so many options but no idea which to go with
Well, glad I could do that at least
how could i make it so the ui's fade in when they are instanced (i know how to do it, i just am not sure how I can fade in the the children of the instance with it)
Add a canvas group to each object, and modify their alpha property, this affects the object itself and all its children
Hey all! New here! Is there a way to load Motions into a scriptable object and then dynaically assign those Motions into the Animator when the player changes weapons to the scriptable object?
So I was trying to implement a file saving system but I am getting IOException: Sharing violation on path when I try to open a streamwriter
is there a best practices for reading / writing files?
using a new Streamwriter(path)
is that on the ctor for StreamWriter? because IOException thrown from the ctor should mean that the path contains an invalid name
might have missed closing a stream...
Most likely there was an attempt in opening the file which was not closed properly, so you now have a dangling stream open
Always use using statements when dealing with streams
They ensure the stream is closed and disposed of properly, even if an exception occurs
using (FileStream fs = File.OpenWrite(...))
{
// use 'fs'
}
// 'fs.Dispose()' called implicitly when execution leaves the block
yeah, my mistake for copying and pasting Microsoft's example code which didn't bother using usings lol
alternatively a using declaration, which is nearly the same thing but doesn't create another scope, is also an option.
using var stream = new StreamWriter(whatever);
and then it disposes of it when the local variable is also disposed (so at the end of the method typically)
Using declaration should be preferred most of the time yeah, but streams are kind of an outlier because some of them have certain behaviors on disposal that you want explicit control of, and using statements allow that.
I've been bitten once by compression stream only writing the final footer on disposal, which happens after I return and thus causing the return value to be missing the footer.
also are there any performance impacts I should be mindful of? I have a slider for a volume setting and I would be writing the value to the file every frame while it's sliding :/
I was thinking it might be safer to only write the value once every x seconds if it's dirty, or only write it once it's done dragging, but that would involve quite a bit more code
Done dragging is a good idea yeah. IO is slow.
No convenient "done dragging" event I can hook into from the looks of it, though π
although the underlying implementation seems to use a unity ui slider... maybe there's something I can expose...
Looks like I have to extend that functionality manually, or add a separate monobehaviour to the slider gameobject to listen for onpointerup
You could probably use OnPointerUp or add a separate save button
I guys, I have a project where I need my program to react to words I say, I found some tutorial on the internet but I can't change the words. Anyone know how to do it ?
https://www.youtube.com/watch?v=nqIJrPswBPE
I try this tuto but when a change the word it doesn't work, it's like it isn't in the code where you have to change what word you have to say
TUTORIAL
https://lightbuzz.com/speech-recognition-unity-update/
SOURCE CODE
https://github.com/lightbuzz/speech-recognition-unity
Learn how to develop a game with speech/voice recognition capabilities using Unity3D and C#. Supports Voice Commands and Dictation.
Brought to you by LightBuzz.
change the word doesn't work ? what
yes, when a change "up" for somthing else it doesnt work and when i said up the bee stop
I think the code change the action of the word not the word them self
You should probably share the code cause this aint helping understanding the issue
thanks it worked
I want to avoid a "save button" as it's not great ux design for things like settings / preferences. So I'm probably going to have to hook into OnPointerUp unfortunately. π
Hey everyone, i am wondering how to convert a vector2 input to a rotation value between 0-360 degrees;
for example i am using the new input system and i want to take the left stick from a gamepad and convert the angle of the stick to the players looking direction in a 2d environment.
any help?
no need
player.transform.right = inputDirection;
(or .up if your sprite is arranged that way)
Is there any easy way to set a param of a function in the Unity inspector from a Dropdown o something similar?
for example, I have this method : public void IngredientSelected(Ingredient ingredient){} where Ingredient is a public enum with some ingredients :
public enum Ingredient {
Bread,
Cookie,
Tomatoe,
Pepper,
Strawberry,
Onion,
Lettuce,
Octopus,
Fish,
Water,
Beer,
Coffee
}
I don't want to make a wrapped method (like this public void SelectBread() {
IngredientSelected(Ingredient.Bread);
}) that call IngredientSelected because I have a lot of ingredients, is there any propper way to make this?
I would do something like every time the value is updated start a coroutine that waits 2-3 seconds then saves. But also cancel the previously started coroutine if there is one.
Are you talking about for a UnityEvent or something?
Simple way to wrap it though:
public Ingredient chosenIngredient;
public void SelectIngredient() {
IngredientSelected(chosenIngredient);
}```
it's on the description of the video
post your code + setup
No, is a simple project. I have to select 5 ingredients in a propper order, each ingredient is like a button and in the method IngredientSelected I want to check if is the correct ingredient or not
right so it's for a button
button on click is a UnityEvent
and you can't pick enums in a UnityEvent
So use this
sorry, yes hahaahah
(put the script on each button)
a ton of games do a save button. Its a lot nicer in some cases because you cant just misclick a setting and have it change without you knowing.
what do you mean by setup ?
idk how much clearer I can explain what a setup is..
Your script, hirerchy objects etc
oh ok sorry
Im not a mind reader, how should I know why it doesnt work on your end by this video only
if it works for them you missed a step or have obvious error
you don't understand my probleme, i download the code from the video and it work, but i cant change the word (they dont do that in the video)
but ther is my setup
I have a gameobject with the main script on it and a image that can move
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Windows.Speech;
/// <summary>
/// see here https://lightbuzz.com/speech-recognition-unity/
/// </summary>
public class SpeechRecognitionEngine : MonoBehaviour
{
public string[] keywords = new string[] { "up", "down", "left", "right" };
public ConfidenceLevel confidence = ConfidenceLevel.Medium;
public float speed = 1;
public Text results;
public Image target;
protected PhraseRecognizer recognizer;
protected string word = "right";
private void Start()
{
if (keywords != null)
{
recognizer = new KeywordRecognizer(keywords, confidence);
recognizer.OnPhraseRecognized += Recognizer_OnPhraseRecognized;
recognizer.Start();
Debug.Log( recognizer.IsRunning );
}
foreach (var device in Microphone.devices)
{
Debug.Log("Name: " + device);
}
}
private void Recognizer_OnPhraseRecognized(PhraseRecognizedEventArgs args)
{
word = args.text;
results.text = "You said: <b>" + word + "</b>";
}
private void Update()
{
var x = target.transform.position.x;
var y = target.transform.position.y;
switch (word)
{
case "up":
y += speed;
break;
case "down":
y -= speed;
break;
case "left":
x -= speed;
break;
case "right":
x += speed;
break;
}
target.transform.position = new Vector3(x, y, 0);
}
private void OnApplicationQuit()
{
if (recognizer != null && recognizer.IsRunning)
{
recognizer.OnPhraseRecognized -= Recognizer_OnPhraseRecognized;
recognizer.Stop();
}
}
}
!code
π Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Procedural animation help
the words are simple strings, just change those then
also yes post code properly
Sorry if this is a bit dumb question, but how I should set the chosenIngredient attribute. This method will be in the LevelManager script
in the inspector
as I said you need to put this script on each button
you should not put it in the level manager script
You can call a function from the LevelManager from this script
braindead example:
public Ingredient chosenIngredient;
public void SelectIngredient() {
FindObjectOfType<LevelManager>().IngredientSelected(chosenIngredient);
}```
But that will be pretty slow - I recommend a better way to get the reference. This is for illustration purposes
That's what I did but it doesn't work
you did what?
you'd have to show the code after you changed it
what does this print
results.text = "You said: <b>" + word + "</b>";
did you look to see what they are set to in inspector?
oh yeah this is public..
probably need to change words in the inspector
new string[] { "cat", "down", "left", "right" };
this will not run again, once it was serialized with previous info
only a Reset would fix it
(another casualty of unecessarily serialized fields)
Thank you for your patience. I didn't quite understand it because when I put Ingredient as a parameter of a function the dropdown didn't appear, I thought that putting it as an attribute of the class wouldn't appear in the Inspector either.
Honestly some simple debugging shouldve told you this, like debugging what was said, or what the contents of the array was
so your code works! do you know how i can smoothly lerp from the current state to the new state with a fixed lerp speed?
yeah use RotateTowards.
Vector3 target = inputDirection;
transform.right = Vector3.RotateTowards(tranform.right, target, Time.deltaTime * speed, 0);```
(speed is in degrees per second. 50 is a good starting point)
does RotateTowards offer a parameter that guarantees a direction? I've had issues in the past where I wanted something to rotate clockwise and it rotated counter clockwise instead because it was a shorter distance
What do you mean by "guarantees a direction"?
no this method will take the shortest path
So I have a monobehaviour attached to a gameobject that has a unity UI Slider
I created a new monobehaviour that implements IEndDragHandler and attached it to the same gameobject but it is not receiving the event
Super basic. I add this script to a gameobject with a slider
Is it because the slider script itself needs to implement these interfaces?
Ah... maybe the issue is I was not actually adding it to the same gameobject as the slider itself... silly mistake. Re-testing now.
Yup, that was the issue. π€¦ββοΈ
can someone help me figure out why this is not working. documentation isn't clear.
here are the values i want to change on the particle system with code.
i want to change the orbitalX vector3 in unpdate method
here is my code not working:
var starMain = psStars.velocityOverLifetime.orbitalX;
starMain.constant = isMoving ? -inputManager.moveInput.x : 0f;```
is it changing inside the inspector ?
you used var so we can't tell. What datatype is that?
Isn't it a struct?
structs are not reference types
you likely need to do psStars.velocityOverLifetime.orbitalX = starMain; at the end
yeah VelocityOverLifetimeModule is struct apparently thats the type
its confusing af because when using main module its also struct but you don't put the value back
https://docs.unity3d.com/ScriptReference/ParticleSystem-main.html
actually this is probably wht you need:
VelocityOverLifetimeModule vol = psStars.velocityOverLifetime;
var orbX = vol.orbitalX;
orbX.constant = whatever;
vol.orbitalX = orbX;```
(the PS module structs are weird and themselves don't need to be copied back)

I finally figured out the issues with explosion collision. first thing was rewriting the code to act like a vision cone to check if the target is behind a wall, then make sure I typed dstToTarget instead of dirToTarget (misspelling mistake :P), finally I added a offset to point the raycast to the center of the target instead of their pivot point in the ground.
i have a projectile that shoots at a specific velocity. but i want that volocity to inherit the velocity of the player. do i just add it? it doesn't seem correct
Yes
its useful when the player is moving
yikers, nice reply
any suggestions how to manage audio/font so that all scripts can easily access it and it is able to be changed from one location. IE a UI click sound that would have to be changed on many different objects? right now I just have an enum for sound type and a dictionary relating them on my audio manager. Is this good enough? For font, I have no idea how to do it.
i have a question about performance.
is it cheaper to have a hundered enemies hold a reference to a prefab, or hold a reference to a prefab manager that is holding the reference?
or does it not matter
it doesnt matter and the second option sounds horrible
its just an example
avoid "managers" imo
only things that ive found a need to have a manager "singleton" was an audio system and save system
why tho?
it creates unneeded dependencies
try to make systems that work on their own
a prefab that is held in your project files already holds the reference for you
there is 0 need to make a gameobject hold it as well
I don't get it, I mean they're managers π
what part don't you get?
maybe i was vague, i mean manager singletons that create dependencies between systems, managers that manager their own systems are not what i was talking about
just my own philosophy
you can just dependency inject down the hierarchy of managers.. they dont all need to be singletons
It would not matter in terms of performance. Both would have their uses. A prefab manager makes sense in some cases
im curious, where would one ever be used
prefabs are for chumps. It's all about having a bazillion SOs and a handful of prefabs
Was that meant for me?
Ah. I use it a lot honestly. I do mostly strategy and rts games. So creating a single manager that handles unlocked and available buildings is useful.
In infinite runners you could do the chunks
In fps's you could have the ammo and other drops
Enemies of course
hm, i guess I avoid most of that using SO's
i see the use cases tho
just depends on which workflow u go with
most prefab managers I use are usually just pooling and those are specific to that prefab type
I have been using unity longer than SOs have been around. I generally try to avoid them whenever possible
how come? I think they are one of the best features in unity but i am new so
I prefer to avoid having a bunch of assets.
I also avoid precise prefabs. I generally have a single enemy prefab that I build custom versions of from my managers
I just really really dislike the way so's are handled though
I have a single enemy prefab that is then changed when instantiated by an SO that it holds
you prefer to just build the enemies through code?
i see, that seems pretty good as well
whats an SO
so you would have some EnemyBuilder and then all the enemies stats/specs laid out in code
and it would pull from that when the prefab is instantiated
Scriptable Object
ahh okay thanks
Basically yeah.
I like SOs because I don't have to worry about overriding the damn prefab instances all the time
lol
and you do run into version problems with people because of that, so I'm not exactly sure how teams work with that
woah really, why
I just had a conversation about it
You can certainly read up to see about my workflow
mb was backreading about the topic
I prefer to do just about everything I can through my IDE.
I've mostly moved to Bevy, which doesn't even have an editor, haha, so it wasn't much different
Plus that way I can make changes from my phone via github lol
I guess i do something similar with my item stats
i just hold a bunch of dictionaries with their tiers, weights, rolls, etc
and then lookup when needed
doing it using SO's would be horrible
i only really use SO's only for storing stats of an object i have in the game, per se i have a weapon object, i can just assign stats to it using the so, but thats pretty much it
And that is a great place to use them for sure
especially like an inventory system its super handy
yeah i use them for my inventory heavily
though they arent necessary, just super nice
you just pass that SO data into corresponding function and ur pretty much halfway done xd
question:
how do i add velocity to a projectile when the player is walking the same direction as shooting?
Can you explain more clearly what you want
Should the bullet move FASTER if you shoot in the direction the player is moving?
Or you want to avoid that?
i want a bullet to come out of a gun the same always.. but if the player is moving towards the shooting trajectory, i want to add the players movement to the projectile, if im walking backwards and shoot opposite direction, the bullet should travel slower
its dependent on the movement of the player
thenjust append the velocity
i have a 2d top down shooter.
Ok. So just literally use the + operator between the playerRB.velocity and the bullet movement vector
this doesnt work because vectors are pointing in different directions
multiply the velocity by the magnitude of your player's velocity?
Yes it does
doesnt work becaus ethe bullet normals are pointing in one direction and the player is pointing in a different direction.
We know
I assume the bullet is FASTER than the player, right?
If so, then it will work
well you would have to scale the velocity as well since if the player is moving faster, it could mess up the velocity while moving backward
this is my code that doesn't work
Vector3 vel = Vector2.up * Time.deltaTime * bulletInfo.velocity;
vel += bulletInfo.playerVelocity;
transform.Translate(vel);
yeah ignore this, i didnt understand what he wanted to do
That is translate
So that changes a lot
I thought you were talking about rigidbody velocity
What is bulletInfo?
i dont want to use rigidbodies, its too intensive for performance with a bullet hell.
it really isn't
is a struct that holds the bullet data
how are you detecting collison then
you probably set it up wrong since I thought that in the past as well
but i fixed my issues with them and the performance is great
with a collider
it may run into issues where you bullets may not register
So, no OnCollisionEnter or OnTriggerEnter
That is what mao was wondering I believe
You're using physics queries?
not for bullets
you should use rigid bodies
kinematic rigidbodies
ok i'll try that i guess
it's physic queries vs OnTriggerEnter
OnTrigger is more performant if you are checking every fixed frame
Overlap is more performant if you are doing it every other num frame
so i would need a rigidbody and a collider ?
i am
and set up your collision matrix to reduce unneeded collision checks
so my character is using a character controller and doesnt allow a rigibody at the same time
so then i just pass the charactercontroller velocity to the bullet. then i dont use deltatime? use fixed update and literally just append player velocity to bullet velocity * speed?
rb has its own methods
rbs will make your life pretty much easier when it comes to dealing things like physics or velocity
wait i dont believe just adding the velocity would work when moving backward
that will cause the bullet to travel backward
I was thinking maybe you can just query overlap around your character and then you can just use colliders on the bullets themselves. The only problem with this that you lose out on interpolation checking, so if the projectiles are faster than the radius of which you check, then they can pass the player without hitting
rb has its own methods of continuous interpolation checks which is the larger reason of using it
as long as you use the rb methods to move
make sure your player is never moving faster than a bullet in regards to this ^
Velocity is a direction.
Ah, was about to write more, but mao got it
if the player is moving faster in the opposite direction
adding the players velocity would switch the direction of the bullets
Yeah. I addressed that above
#archived-code-general message
ah okay
though adding velocity will make the bullets travel in a slight sideways direction
But yeah, that is an important consideration
if your player is moving perpendicular to the bullets
my code is totally not working. im not understanding how to apply this movement
here is my code
public struct BulletInfo
{
public float halflife;
public float velocity;
public float damage;
public Vector3 playerVelocity;
}
public class Bullet : MonoBehaviour
{
public BulletInfo bulletInfo;
float elapsedTime = 0f;
Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
elapsedTime += Time.deltaTime;
if (elapsedTime >= bulletInfo.halflife)
{
Destroy(gameObject);
}
}
private void FixedUpdate()
{
Vector3 vel = Vector2.up * bulletInfo.velocity;
vel += bulletInfo.playerVelocity;
rb.MovePosition(vel);
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.GetComponent<Enemy>())
{
other.gameObject.GetComponent<Enemy>().Damage(bulletInfo.damage);
FindObjectOfType<SoundManager>().PlaySound();
Destroy(gameObject);
}
}
}
if you can store the speed you can just apply the speed to the forward direction
don't mind the bad structure. i literally just started this project today and will clean it up when i move on to the next thing
if a rigidbody has any velocity, it is moving already
so you just set the velocity once
you don't need to move posiiton or anything
oh wow ok
so when you set the velocity, you would also take into account the player's velocity
deltatime bullets is bad without a lot of extra work you probably dont want to do
but i believe adding the velocity will not work correctly
since this ^
That code also makes no sense
You're plugging a velocity into MovePosition
Which wants a position
velocity is a vector
So what?
you set velocity to any vector, it will move in that direction
im just stating that, not responding to you
MovePosition moves to a specific position you give it
i dont think dillan understands that since the moveposition stuff
Velocity doesn't belong as the parameter
the bullet shouldnt even think about its own velocity really
your "gun" should be doing that
ok what about this?
public struct BulletInfo
{
public float halflife;
public float velocity;
public float damage;
public Vector3 playerVelocity;
}
public class Bullet : MonoBehaviour
{
public BulletInfo bulletInfo;
float elapsedTime = 0f;
Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
elapsedTime += Time.deltaTime;
if (elapsedTime >= bulletInfo.halflife)
{
Destroy(gameObject);
}
}
private void OnEnable()
{
Vector3 vel = Vector2.up * bulletInfo.velocity;
vel += bulletInfo.playerVelocity;
rb.velocity = vel;
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.GetComponent<Enemy>())
{
other.gameObject.GetComponent<Enemy>().Damage(bulletInfo.damage);
FindObjectOfType<SoundManager>().PlaySound();
Destroy(gameObject);
}
}
}
this code is making the bullet go upwards always no matter the direction i am and the forward vectors
well, you can moveposition using the transform's location + the velocity
can you write a small example of what you mean
dillan send the code where you instantiate your bullets
rb.MovePosition(transform.position + delta * speed * direction)
ok
public void FireShot()
{
Bullet bullet = Instantiate(bulletPrefab, bulletContainer);
bullet.transform.position = transform.position;
bullet.transform.up = inputManager.lookInput;
bullet.transform.Translate(Vector2.up * .65f);
bullet.bulletInfo = bulletInfo;
bullet.gameObject.SetActive(true);
}
this code is not adding the players velocity yet. i'm just trying to get it back to working properly
you should set the velocity there
https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
Im just going off the docs here
also you dont need to set the and all of that, you can do that all in instantiate
i'll change the way i'm doing it after it starts working
whats the difference between that and initializeg velocity OnEnable? how does that change anything?
your bullet doesnt need to know about the player since the player already knows about the player
which i assume the gun is attached to
you avoid having to pass it in through bullet info
it should work, just makes a bit less sense
Vector3 worldMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = (Vector2)((worldMousePos - caster.transform.position));
direction.Normalize();
Projectile projectile =
Instantiate(projectilePrefab, caster.transform.position + (Vector3)(direction * 0.5f), Quaternion.LookRotation(Vector3.forward, direction));
this is how I do it
then set the velocity to direction
so you pass the velocity in the Quaternion.lookrotation?
yes
read up on quaternions if u wanna know why, i dont even fully understand them tbh
So, I figured out how to add my anchor data to custom image elements and embed them in my graph nodes, but I ran into an error specifically with asset selection menu that would normally appear when clicking on an object field like in this picture. It throws a null reference only when clicked, but you can drag and drop images in as normal and it seems to work correctly.
Does anyone know if getting that asset selection menu to appear is a property of using manipulators?
how do I allow a variable to be seen in inspector, but to not allow its value to be changed (from the inspector GUI)?
use something like naughty attributes or make the attribute with some editor coding
you can also use Debug mode to view private vars
how could you make the attribute oneself?
thanks, I don't dive into editor stuff all too often
ya pretty fun stuff
do you know why the enemies in my game are looking kinda choppy almost low framerate? should i remove riggid bodies from enemies? the enemies stack up quite alot
mess around with it
try kinematic, ect
but otherwise if you don't need it (dont care about knocking back enemies) you can probably ignore it
there's a lot of things you can try, but most falls into how you're doing a lot of the pathfinding
it doesnt make sence though. i only have like 25 small enemies on screen with nothing but movement and it's choppy
then that's somethign to profile yourself
this is the only code i have on enemies
private void Update()
{
Vector3 direction = (player.position - transform.position).normalized;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
rb.rotation = angle;
moveDirection = direction;
}
private void FixedUpdate()
{
if (player)
{
rb.velocity = new Vector2(moveDirection.x, moveDirection.y) * speed;
}
}
turn interpolate on
oh right that's probably it
should consider MoveRotation though as instantly changing the angle like that isn't lerp'd
ok
wow that made a hugee difference. looks 100% smooth now
anyone who has used NaughtyAttributes know if it's possible to hideif OR between a bool and an enum
or use multiple hideifs/showifs
that can be easily done with uitoolkit (custom editor)
oh didnt see it's about naughtyattributes
the docs show you can specify methods to check
otherwise you can use multiple flags
[ShowIf(EConditionOperator.And, "flag0", "flag1")]
public enum EnumType
{
entry1,
entry2,
entry3,
}
EnumType enum1 = EnumType.entry1;
EnumType enum2 = EnumType.entry3;
[ShowIf("EnumCheck")]
public float myFloat;
public bool EnumCheck()
{
return enum1 == EnumType.entry1 && enum2 == EnumType.entry3;
}
thanks
oh, substitute one check with a bool as I misread that
it gives an error for balletScript.balletSpawnpoint = new Vector3(balletScript.transform.position.x,balletScript.transform.position.y,0f); line
NullReferenceException
but how ??
You don't assign balletScript anyhwere, so probably that
None of this involves assigning to the variable balletScript on SliderController
fixed thanks π
any suggestions how to manage audio/font so that all scripts can easily access it and it is able to be changed from one location. IE a UI click sound that would have to be changed on many different objects? right now I just have an enum for sound type and a dictionary relating them on my audio manager. Is this good enough? For font, I have no idea how to do it.
Make a audio-player component that has a method (or parameter on a single method) for each sound you want to play and reference that component in all your sound-triggering components. Alternatively have the trigger component find the audio-player through a service locator (pattern), inject it on instantiation or, if you want to go down the route of bad architecture, make that audio-player component a singleton.
can you elaborate on the first one? So everything that plays sounds will have a component that holds all the possible sounds?
Another way would be to only have a centralized audio-clip provider (similar to the player above) that returns only a clip for a given sound-key and you play that locally. This could be a scriptable object.
ah so I could just plug that SO into everything that would play a sound
No
Yes
same
you just have to make a script that assigns the font n awake/start to the text component
kk thanks
what is the benefit of using a service locator?
entity.stats vs gameManager.entity.stats
make everything a singleton vs make one thing a singleton
seems like a lot of hassle for not much gain since I only have a Save and Audio singleton
and nothing really depends on them
yeah usually not a big deal for single use type managers
I find it cleaner though just to reference by some super manager
yeah i made my game in a way that avoids most of that, nothing communciates through singletons
true
all my singletons are basically read only or have some public functions that do something that is not needed by any class ie play audio
probably can get rid of them in general tbh
so i guess the big benefit of a service locator is when doing additive scene loading
so things can essentially talk through different scenes
Itβs the best compromise between bad architecture and convenience for discovering the βmanagerβ of a dynamically spawned component in small/solo teams. Mostly because it can be the only singleton and you can use it in a way that you donβt create coupling all over the place and retain some control over what the locator returns for a given type, which helps a lot with testing.
Itβs more work to write a singleton than it is to use a simple service locator imo. I constrain my use of the pattern to one cached call per lifecycle object and only if static references are impossible. Also the registered services are immutable after scene/level startup and all services register as interfaces.
Ok i'm asking here since this seems kinda simple. I have a list of 'cities', and a total population. I want to distribute the total population between the cities, not evenly. I have a texture2d that i want to act as a heatmap, to give weighting to some cities over others. I can't figure out what to do to assign each cities population correctly as i loop through them though
i have a weird problem. i'm using instantiate for bullet system and problem is when i use slider control to move right, it shots clone bullet with original bullet. but this problem happens only when i move right
don't have the bullet object actually in the scene, use a prefab
public void OnSliderValueChanged()
{
aticiUcu.transform.rotation = Quaternion.Euler(0f,0f,-sliderComp.value);
balletScript.balletSpawnpoint = new Vector3(balletScript.transform.position.x,balletScript.transform.position.y,0f);
}```
the issue is likely that the new bullet is colliding with the "original" when rotated in that direction
You think needing a 2 way dictionary is a sign of bad design?
That or just 2 dictionaries.
@somber nacelle i removed it from scene but now it doesnt let me assign gameobject that i marked
in prefab
i cant assign it
prefabs cannot reference in-scene objects. pass the reference when you instantiate it
I have objects that I want to ID. I have a manger class that allows me to "register" objects to be ID'd.
I'm finding that I want to be able to both ask the manager "Hey I have this ID, can I have the object" and "I have this object, does it have an ID?"
I can solve this by usng 2 dictionaries (Object to ID and ID to Object). Do you think this is bad practice?
Hello friends
how can i do it
thanks
hi, how would you build your architecture if your game has a multiple of game types such as 5v5, battle royale etc. and they can be playable as team vs team or free for all or bot of them
Well really the only thing that matters here is defining who is an ally and who is an enemy.
Cause in a team based game you do need to make sure their are specific interactions against allies.
While in something like a free for all, everything is technically an "enemy".
yeah but game tpye needs to know if its a team or free for all, for example capture zone game needs to know all zones has captured by the same team
hey lazy i finally got that ability system I was working on months back in a working state lol
pretty proud of it
i appreciate the help u gave
Glad to hear it, and no problem.
Sure. I mean you're going to need some high level manager to define the rules/properties of the match.
Team size, number of teams, etc.
I mean technically in a free for all everyone is on their own team π
I could have sworn there was some way to return a list as ReadOnly without creating a new object.
Is this the right place to ask a question about GPS using Unity - I'm trying to make it work on my phone but the LocationService is hanging on Initializing
I got perms enabled, tried both fine and coarse perms and changed the LocationService parameters
I've tried it using handheld as well as an emulator and I'm still getting it to time out
(The emulator timed out with prebaked GPX data)
IEnumerator Start()
{
if (!Input.location.isEnabledByUser)
{
statusText.text = "Location service is not enabled. Please enable it in settings.";
yield break;
}
statusText.text = "Initializing location services...";
yield return new WaitForSeconds(3);
UnityEngine.Input.location.Start(500f, 500f);
int maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
{
yield return new WaitForSeconds(1);
statusText.text = (20 - maxWait) + " seconds...";
Vibrate();
maxWait--;
}
if (maxWait < 1)
{
statusText.text = "Timed out. Try moving to an open area or check your GPS settings.";
yield break;
}
if (Input.location.status == LocationServiceStatus.Failed)
{
statusText.text = "Unable to determine device location. Please try again later.";
yield break;
}
else
{
statusText.text = "Location services initialized.";
StartCoroutine(CheckLocationRoutine());
}
}```
Specifically
maybe ask in #π±βmobile
okok
uh i have a problem error c#
You have typed some invalid C# code.
start by making sure that your !IDE is configured so you don't make simple syntax errors, like comparing a char to a string
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
Hello, I have problem with a project using this tutorial about Unity Multiplayer Alteruna:
https://www.youtube.com/watch?v=E9eHefMpVnM&ab_channel=Bobsi
Connection through the server works, rotation works but does not synchronize movement
What's the problem?
!collab π
We do not accept job or collab posts on discord.
Please use the forums:
β’ Commercial Job Seeking
β’ Commercial Job Offering
β’ Non Commercial Collaboration
and don't crosspost
for the unity timeline, is there a better way to trigger functions outside of the signal emmitors? the signal emmitors are pretty uncustomisable and will clunk up my project with a bunch of assets
Timeline actively discourages any kind of event usage so it cant be abused as a programming instrument
I have Vs Code but I'm not really good coder just using modified scripts ||I'm a bad coder||
okay so get vs code configured
so what would i do instead? Im making a game with similar mechanics of detroit become human so its gonna have heaps of cutscenes
what now?
open your code?
i really shouldn't have to hold your hand through something so simple
This issue occurred a few days ago and was fixed by Unity, it was a fail on their side.
Log out, log back in.
Also, wrong channel to post this in!
thanks and sry for the wrong channel
Use it just for cutscenes?
do you make it ?
anyway it's not using chatGPT
I would just make 2 functions to do a lookup on 1 dictionary, I find using Linq the easiest way of doing this, for example FirstOrDefault will return the first object that matches your ID, if your ID does not match any object, then default is returned instead, so you can treat it as a "null condition" - and vice versa, if the object is null, you can return -1 for the ID and handle that as a "null condition" as well, and if the object is not null, you can return the objects ID property - with Linq, theres a bit of GC cost, with a copy of your dictionary theres a memory cost, and from what your describing I dont think you would absolutely need the copy to do a "reverse lookup" (alternative to Linq, you could also use a foreach loop and check each element for a matching ID or use HasKey if your ID is used as a key, or Contains/Exists otherwise)
For my game, I used a SO to describe the game mode and data thats consistent across all game modes (player count, team sizes, match time, etc), then a manager in its own scene that takes the SO and creates a interface of IWinCondition, basically acting as the game rules, that manager subscribes to the servers tick rate instead of Update to check every server second if the win condition has been met - I can then make specific game mode scripts that inherit that interface for example TDM:IWinCondition can decide if one team has been eliminated, or if the teams score is >= whatever the SO says, or if the match time has ran out (if that mode has a time limit), or if all 5 capture zones are owned by 1 team ID, etc - I can also do the same extension with the SO if for example TDM also needs to specify a number of capture zones or kill count to win, I can have a TDMSO : GameModeSO - my approach uses a manager, through inheritance can become a game mode, defined by a SO, through a interface, but not the only approach, with any approach you take, youll want to make sure you have a way to execute game mode-specific logic and rules, I chose a interface, since TDM can also be a Mono and replace the standard manager in the match or handle custom games if I wanted to
i had a qusetion
i have a pathfinding algorithm that i coded
that returns a list of vector3 points
and i want to use those points to create a road mesh and am lost as to how i wouuld do this
you probably want to look into the Splines package
That's a pretty vague question. The short vague answer is "procedural mesh generation"
i just want to make a road between the start and end
ill look into this
yes and the way to do that is procedural mesh generation
which is just a fancy way of saying "creating a mesh with your code"
Does the Resources folder not work for builds of Unity games?
I'm trying to run a build of my game and it can't seem to access anything from the resources folder
Resources works fine in builds.
show more details of your issue
make sure you are using Resources.Load correctly https://docs.unity3d.com/ScriptReference/Resources.Load.html
I bet they're trying to add files to a Resources folder in the build and load them
depending on what you're trying to do, StreamingAssets folder might work better for you
This is what I've got in my code
And then this is my folder:
and what is the filepath
probably need the extension too
No, Resources doesn't work with extension
have you checked the player logs to see if there are any errors reported
So can you show logs from your build when it doesn't work properly?
I would expect to see:
"Looking for file: some/path"
"No audio clip found"
for a clip that actually exists
Where would I find the logs for builds?
!logs
Log file locations:
https://docs.unity3d.com/Manual/LogFiles.html
You want the "player logs"
There doesn't seem to be any Editor.log in that folder
you're looking for the player logs not the editor logs
player log
You can also attach the debugger to the game process to be able to both see the console and step through the code.
Ahh found the player log now, lemme take a quick look through
Ok that's weird, instead my log file appears to be clogged with something breaking at the very beginning
Basically my game has a "Dialogue Menu" of sorts, and the Dialogue Menu gets updated after each person has finished speaking
So I figured there was an issue loading the audio files
But it seems like there's an issue initialising the menu
Not sure why that would happen if it doesn't have that issue running from the editor
what's in the updateButtons method
probably an order of execution issue
that's the typical reason builds break vs the editor
but yeah now that you can get at the player log you can start debugging for real!
oop that's a lot of potentially null objects
Ok I'm back with a more exact issue, I just don't understand why
it should, you may just need to import it by name if you don't see it in the package manager
com.unity.splines
Why do i get this error ? It a ppeared out of nowhere when i edited a different script and i have no clue what could cause this
For some reason it can't find my Json file in the build?
the Assets folder does not exist in a build btw
Yeah so I'm gonna have to try redirect that, what path would I put in to read a file so that it will work in an actual build?
you could put it in the resources folder and load it with Resources.Load or you could throw it in StreamingAssets, or you could create the file if it does not exist at your desired path (such as in Application.persistentDataPath) and read it from there if it does
if the file is immutable and not something you want the player to have access to, another option is TextAsset and not bother with paths at all
ah yeah, true. i forget that exists
are you sure you're on 2021 π€
those errors indicate that there is an issue with using a target typed new which is perfectly valid in 2021
yeah im p sure
2021.1
why
my school project requires me to work with that π
my teacher was unwilling to let me use a more recent version
wait so can i js not use splines
well that's too early to use c# 9 so π€·ββοΈ
oh
pretty sure even the oldest versions of the splines package require 2021.3
is there any other option that i can use to make a road mesh out of vector 3s
have you googled how to make roads via code?
yeah i tried
how many total errors? you can embed the package into your project and then fix the compiler errors
https://docs.unity3d.com/Manual/upm-embed.html#embed-cached
Finally solved it, thank you so much I was really worried that I wouldn't be able to get this to run in time π
Hello guys, I have some issues with drag & drop with UIDocuments (during gameplay).
So my problem is the following: I
have a UIDocument that is representing an inventory, I made the inventory window draggable with PointerEvents.
I did the same for items inside items slots. Whenever the item is dragged outside the window of the inventory it starts "teleporting" or acting funky, any idea why that might happen?
Can someone help me with this ?
Could you share the code?
there is no code its from Lozcalized strings something
how can I manually update to 1.5 localized strings ?
Hello everyone. I want make a object rotation and check when my character did a somersault. But i cant realize how to debug degrees in console. Maybe anyone can help?
check when my character did a somersault
Can you explain in simple terms what you mean by this?
do you want to know if the object is upside down?
it's really better not to try to read euler angles to do that
gimbal lock is going to kick your ass
i need to check when my character made a 360 degree turn.
I would probably continue developing and making sure to get Unity/package patches as they come.
how do you suppose reading angles is going to help you with that?
euler angles are a bad idea almost always. What you really want is Vector3.SignedAngle
this way you can define the axis of rotation you care about and not get killed by gimbal lock
i dont know yet but i want to see degrees in console from transform component
transform.localEulerAngles
but I'm warning you nothing but sadness lies that way
Thanks a lot.
Yes. i know. It us just testing.
not final version.
If I'm using a rule tile, how may I check which particular tile is going to be placed at a particular cell position (via code)?
No need to ping me, especially twice π
Now, one thing I see is that your fps tracking is messed up badly.
You should at LEAST yield return null (not .2 seconds...)
Two, is this a kinematic rigidbody
@loud stratus - what are you trying to accomplish with particles? You can sort of go about it either way, so it depends on your use case.
Then you probably should not be using MovePosition
Also, have you used a profiler to actually verify the issue?
And in the hierarchy view, what is taking the most time?
Quick UI coding question: How do I use a Multiple 2D sprite as background image in my UI Style Sheet?
hey, im making an android game but when i compile i get an "Gradle failed to build" error and it says to check the console for more info, but i do not know what these errors mean and i cant find help on google/youtube, can somebody please help me?
I am currently trying to make an object rotate at an offset around the player. How can I accomplish this? What I am doing currently: cs void RotateObject() { Vector3 desiredRotation = Vector3.Lerp(rotatingObject.transform.forward, -camera.transform.forward, 1 - Mathf.Pow(smoothing, Time.deltaTime)); rotatingObject.transform.forward = desiredRotation; } void PositionObject() { Vector3 position = camera.transform.localPosition + objectOffset; rotatingObject.transform.localPosition = Vector3.Lerp(rotatingObject.transform.localPosition, position, 1 - Mathf.Pow(smoothing/(Mathf.Pow(1, 100000)), Time.deltaTime)); }
So open that up and find the actual thing.
That is a LOT of allocation calls too.
Doing yield return new allocates a new thing everything time, but that isn't gonna be all of it
Yes... open that
This is what the code snippet does currently
Editor loop is irrelevant. And nothing useful is showing here.
It is all collapsed
if boundsPosition = (0,0,0)
how is it possible for ChunkGridBounds a struct of type BoundsInt, to not contain said position?
NVM, it seems for boundsInt, if your point is touching/equal to the MAX bounds, it is not considered inside the bounds
How can I make this object rotate around the camera without parenting the object to the camera?
just offset it to camera world position
you will have to constantly poll camera world position and offset the radar position to it
you can use one of the animation constraint components like the PositionConstraint or ParentConstraint
This is code for my camera for a 2.5 endless runner for mobile,
using UnityEngine;
public class TrackingCam : MonoBehaviour
{
public float followSpeed = 6f;
public float smoothingFactor = 0.1f;
private Vector3 velocity = Vector3.zero;
void FixedUpdate()
{
Vector3 targetPosition = transform.position + Vector3.right * Time.deltaTime * followSpeed;
transform.position = Vector3.Lerp(transform.position, targetPosition, smoothingFactor);
}
}
The issue is when the follow speed is 6 which is the pace i want my game to be the backgrund and coins all become blurry with motion, so is there a way i can keep the speed but get rid of motion blur
Im not using motion blur from PP
can i use it to get rid of it?
URP
change the update mode on the camera
perhaps, you could use Cinmachine vcam
doesnt seem like u are using it
just for reference, both the coins and bees are blurry
fixedupdate is ur problem
dont run ur code in there
try running it in update and change the frame rate
the framerate needs to be 30 for mobile, and okay let me try that
Here is how to change framerate incase u are unsure
any suggestions on how to improve this code? i feel like it is very inefficient https://gdl.space/erabevizeb.cs
give a quick summary of what is going on here my friend
this calculates the damage recieved based on elemental resistance, dodge chance, and crit chance
im only looking for optimizations since the code works fine
is list<keyvaluepair> the best choice here?
etc
damagetype is just an enum with types such as physical, fire, etc
Pre-optimization is the root of all evil
if it works fine, move on to greener pastures my friend
i like to optimize, im just asking if theres anything glaringly wrong
ok, let me take a look
since this will be called 100s of times a second
why will this be called 100s of times a second instead of once when damage is emitted/contacted? .. that's going to be infinitely more productive than trying to optimize this chunk of code
100s of times a second was hyperbole, my game will have 100s of enemies on screen and when they are damaged, this is going to be called a lot
if there are 100s of enemies on screen and this method is called once when the user casts a spell or whatever, that's insignificant and you should move on
basically start optimizing when you have a hot path called >1k times per frame or second
yes I understand, i want to use it as a learning opportunity for the cases to use list<keyvaluepair> over dictionary
im asking a simple question, i understand its insignificant
You could prob put all of this in one loop
buuuuuuuuut.. what i see: 1) don't allocate the out list every frame, cache it and reusue it 2) the "helpers.percentchace.current" is smelly code, it doesn't seem like it should be a bool based on the naming convention, and has very little in the way of guard clauses (high bug surface here - array index out of bounds, NRE, etc); 3) foreaching over ratios to allocate a new KVP is also wasteful - don't allocate (new) in hotpath if you can avoid it.. 4) you foreach again in final damages with a bunch of fragile calls (no guard clauses, you're gonna have array out of bounds and NREs and have a heck of a time debugging it later), and you also new in the second foreach..
Helpers.PercentChance is called with the param that has .current
i think you misread it
you asked a simple question but the simple answer wasn't what you expected - it was "don't optimize this but instead optimize the code that's calling this".. and again, optimizing early is irrelevant until you have some data that indicates that the hotpath is problematic.. i'd wager that even as clunky as this code is written it's only taking a few nanoseconds per frame and ultimately not worth the attention
i appreciate it though
i understand the code - and why is it .Current and not .IsCurrent or .IsActive or something else that indicates it's a bool? target.stats.current reads in english as "this is the dodge stats current value" not "this dodge stat is current/active"
i am calling the Helpers.PercentChance function passing in the current crit chance value, i believe that makes perfect sense
language matters - and it's not just for your coworkers (or us), but for you own readability later when you can't figure out why this method is NRE'ing or off-by-1ing
Good semantic calls,
Great call on caching that list of keyvalue pairs
"PercentChance" is not a verb - methods should be verbs
GetPercentChance() or TryCalculatePercentChance() are method names, PercentChance is a property name - again, putting the ()s on it makes it a method (obviously) but readability matters and this is named wrong
okay, though the "current" refers to the float value associated with that stat
isCurrent would make no sense
Helpers.PercentChance() in this situation is doubly badly named, because it's not a verb, and it doesn't indicate that it returns a bool
kk, switched it to GetPercentChance
so why does Helpers.PercentChance() return a bool? it's very difficult to understand your intent from your naming convention, and if we (I) get hung up on trying to understand your intent from poorly named variables it's doubly difficult to assess what you're asking for, which is optimization .. hope that makes sense
yes, i appreciate the help, all the function does is return Random.Range(0, 100) >= 100 - percent;
so if you pass in 60, it will roll a 60% chance
it shouldn't be GetPercentChance then if it returns a bool - what does it do? IsPercentChancePositive()? or DidDodge()?
ok then i'd rewrite it to be more clear:
float chanceToDodge = target.Stats[Stat.Dodge];
bool didDodge = Random.Range(0,100) < chanceToDodge;
if (!didDodge)
{
// do some damage
}
see how much easier that is to read and understand? being a good programmer/developer isn't about being clever and trying to jam 100 things on one line, it's making sure that your code is easily readable so that when you need to maintain it a year from now, or when you need to debug a problem with it, it's easy and obvious what the problem is
I know it's a little tangential to what you're asking for but .. it's still important and what I would tell a junior who brought this to me to fix
kk, thank you
i also don't understand the casting of crit damage to an int and then putting it in a KVP with a float .. but it looks like you have some mage going on here with finalDamages
don't use var - you're obscuring your intent.. requiring the reader to find the declaration of finalDamages to figure out what is the purpose of finalDamages.IndexOf() is doing - and also, it's likely that this is a terrible use here.. indexOf needs to iterate the entire list to find it.. instead you should use a dictionary and just reference the item directly by a key
(line 21)
the int/float stuff is left over from when I was undecided on if I wanted damage to be only ints or floats, will fix that
foreach (var damage in finalDamages) // iterate final damages
{
int critDamage = (int)(damage.Value * (100 + caster.Stats[Stat.CritDamage].Current/100f));
finalDamages[finalDamages.IndexOf(damage)] = new KeyValuePair<DamageType, float>(damage.Key, critDamage);
// ^^^^^^^ iterate final damages again - for loop within a for loop = O(n^2)
}
can you format that a bit
ah i see
so indexOf just loops over
so it would be better to just make a dictionary instead
despite the additional overhead
if it's a list, yes, which i don't know if finalDamages is until i find out where it's declared (up at the parameters) - ie, don't use var
you're not at the point where you have to worry about overhead
you're at the point where you have to identify the correct data structure for the application
list = do something to everything
dictionary = do something to one item
hashset = check if one thing exists/doesn't
start with that
okay, my thought process was that if I don't need to index into the container a lot, which I wont unless I need to access that specific damage type, IE if a player dies to it to display the damage and the type they died to, I don't need to make a dictionary for it
i'm not sure what ratios and finaldamages are for your parameters (they're poorly named) but I'm .. guessing? that you have some sort of multiplier for damage types (based on the targets resistances? weaknesses?) and you want to output the final damages for each damage type?
yes, so a given ability will have a ratio of damage say it does 60% fire and 40% physical
and will take the players stats based on that ratio
or even 500% physical, etc
if the target has fixed ratios you don't ... make a list of KVPs, you just use a dictionary:
Dictionary<DamageType, float> damageMultipliersForTarget = ...; // property of target
Dictionary<DamageType, float> damageMultiplierByCaster = ...; // property of caster
public static float GetDamageDone(AbilityCharacter caster, AbilityCharacter target, out Dictionary<DamageType, float> damageDone, out bool didCrit)
{
damageDone.Clear(); // requires init outside this method
didCrit = false;
float damageDone = 0f;
foreach (var kvp in damageMultiplierByCaster)
{
DamageType type = kvp.Key;
damageDone += target.damageMultipliersForTarget[type] * rawDamage * caster.damageMultiplierByCaster[type];
}
return damageDone;
}
something basically like that
obviously you have some additional stuff going on, crit chance, etc, but you should just iterate the damage types once
this pseudocode also assumes you have well-formed dictionaries, but.. yeah, basically, iterate the damage types once and do the calculations with a dictionary lookup (which is fast - compared to IndexOf() on a list) and then return the sum.. it's also much more readable and understandable and more bug resistant to off-by-one-errors and NREs
// this line can fail in all the ^ places
var value = new KeyValuePair<DamageType, float>(ratio.Key, (int)(caster.Stats[StatParser.GetDamageTypeToEDamageStat(ratio.Key)].Current * ratio.Value));
// ^ NRE ^ NRE ^AOOB ^NRE ^NRE ^NRE ^NRE
most of the time? it won't, but it makes a lot of assumptions that all the data is well formed and has no guard clauses to check for problems
yeah I see why, though in those functions it would be impossible to be missing the value
unless null is passed in
fine but they should still do the guard clause checking
yeah, i will check for null
your methods should always assume bad data sent and fail nicely (and preferably log it)
because if you do see the log message you instantly know what the problem is and how to fix it
and if you don't see the log message, you don't see the problem, and maybe you get weird behaviour that you have to step through code to try to figure out = the worst possible use of time
cheers gl
Turning on NRT would save you from all those unnecessary null checks and essentially move them to the responsibilities of the compiler instead.
opinion time/hot take: NRT sucks
That's not really hot, C#'s NRT is not great, in particular the language wasn't designed with NRT in mind from the start and has a ton of baggage, and Unity doesn't help that none of the API is NRT aware.
still not sure of the best practices for null checks. I seem to just stick them into every method that takes some reference just for the heck of it
In languages where design takes null into account from the start, it's amazing.
AbilityCharacter? character = GetCharacter(id); // should this return null? throw an exception? when character w/ id isn't found
If it returns null (successful failure), you still need to check for null. If it throws, you need to try/catch.. more work and uglier code imho
That's completely missing the point
If GetCharacter returns AbilityCharacter, you don't need to null check; if it returns AbilityCharacter?, yes you need to null check before using it, and the compiler will tell you you need to null check.
I mean, I've used all the schemes - NRT, response/return types wrapped, and just default nullability without all the NRT nonsense.. I just prefer the non-NRT stuff since it just puts a lot of burden to null check everywhere instead of only "on the border" .. I just don't think it catches enough sneaky NRE to make it worth the hassle
Similarly if you have a method void DamageCharacter(Character character), then compiler will prevent you from calling DamageCharacter with possible null, so your DamageCharacter does not need to do null check at all; if you have void DamageCharacter(Character? character), then compiler will force you to do null check.
again, just opinion.. probably objectively wrong anyway, but you'll never get me to go back to a NRT project voluntarily π
(fwiw my server codebase of 100k+ lines is NRT since it is required for the blazor/razor admin tools - i went down kicking and screaming with the addition of NRT)
Honestly, if I would put more effort into my event systems I could avoid a lot of unnecessary null checking as a null invoke would simply mean that the reference had not be subscribed so there's no fault in the logic there.
It's different if you are turning on NRT on a legacy code base that didn't write with NRT from the start though.
i wrote the code from scratch, myself
If you have NRT from the start, it's a completely different experience.
I still hate it :p
Modern languages that don't share the mistake of what C# did, are generally so nice to work with. I've never wasted any time on NRE in those languages, because compiler stops them from even happening at all.
https://gdl.space/hudeqadobe.cs this look a bit better?
It's no different from compiler stopping you calling GetCharacterByName(42) because name argument is supposed to be a string.
Beyond just null checking everywhere, what I do have problems with is duplicate logging warnings. Sometimes I run into a situation where my help method returns the issue, but the method itself that called the issue has a similar log warning.
^ it's a gateway to a much cleaner code π. if the possibility of nulls can be prevented while you're coding, why not! (not all should/must be prevented tho)
Hey. I want to make a pause game feature. How can I make it an event and observable? So methods are invoked when the bool changes?
Make it an event, exactly
Are you asking "how do I use events in C#"?
What's the best way of writing it so that it observes changes and invokes on that trigger?
My idea was setter but properties don't work
public Action<bool> OnGamePaused
{
get { return _isGamePaused; }
}
private bool _isGamePaused = false;
what
I am having an issue with Vector3.SignedAngle right now.
Here in these two images, the code is working just as intended, attached below
Vector3 from = transform.right;
Vector3 to = a.position - transform.position;
print(Vector3.SignedAngle(from, to, transform.forward));
Debug.DrawRay(transform.position, from, Color.green);
Debug.DrawRay(transform.position, to, Color.red);```
However, this breaks down when I move the target object a along the z axis? This is specifically the reason I use signed angle, I thought that this would negate any movement on the normal passed into the function
Attached is it not working
you are mixing up the property and the event. They're two separate things.
Yea. So they don't work together in this context
Incompatible type
they work together just fine you're just doing something weird
public event Action<bool> OnPause;
void Update()
{
// when some input
OnPause?.Invoke(paused);
}
How do you check if it is paused or not?
GetPaused
thats unrelated
public static event Action<bool> OnPauseStateChanged;
private static bool _isPaused = false;
public static bool IsPaused {
get => _isPaused;
set {
if (value == _isPaused) return; // do nothing if we're not changing the value
_isPaused = value;
OnPauseStateChanged?.Invoke(value);
}
}```
For example^
That's my goal
any subscriber to OnPause will receive the bool as argument
public event Action<bool> OnPause;
void Start()
{
//sub to OnPause
OnPause += HandlePauseStateChange;
}
void HandlePauseStateChange(bool value)
{
Debug.Log("Pause is: " + value);
}
Ah I see. Is this good practice though? Since surely that is a side effect inside the setter?
setters having side effects is the entire point of having setters
Why else would you ever write a setter?
Just use auto-properties at that point.
invoking like that from within setter is standard practice
I honestly just thought internal calcuations like maths or something of that sort
UniRx had it called ReactiveProperty
fair that's one other reason to use setters. But the main reason is to do things like fire off events to make things observable
Good to know. Will defintely be using this a lot
Thanks both of you
Hi guys, from reading online, I expected that if I do a Physics2D.raycast from inside a collider, no hit will occur on that collider. But in practice I think its happening. So I wanted to confirm with you. Is it normal that a hit occurs when raycasting from inside a collider?
instead of thinking its happening, debug to prove if it is. debug the name of what was hit, where it was hit, where the ray started
the normal is the plane on which the 2 lines are, by using forward and not up, your lines intersect this plane, i think its the issue
Well the lines aren't supposed to intersect and rarely will. I'm trying to make a bolt action mechanism and am struggling with the actual rotation part, the bolt should rotate itself on the Z based on where the hand is around the bolt. I dunno if this is even the right way to go about that
The bolt rolls around the forward axis, which is why I am using that
Imagine that target ball as the hand position and the object as the bolt
It shouldn't matter how far back or forward the hand is, only the X and Y angle of the hand relative to the bolt
anyone know the function to round a float to the nearest 100th?
Multiply it by 100. Round to nearest int. Divide the rounded result by 100.
that works too lol
Do note, however, that 1/100 and many multiples thereof do not get represented nicely in binary.
also if this is to display something in a UI label, you can just use the formatting strings
ah yes it is
myFloat.ToString("F2")```
you can try flattening the to vector so that its z equals to a z
i cant completely picture it but they have to be in the same plane, my guess is that cross product changes if you move one of the direction vectors off the plane
@runic nimbus
thank you
Gotcha:
Do not expect the "from" and "to" vectors to be flattened against the Axis when calculating the angle. If the inputs are pointing at all up or down in the plane defined by the axis, you're going to get the "Angle between two 3D vectors" returned. NOT the "Angle between two 3D vectors flattened on a plane".
Workaround: Make sure that you flatten the "from" and "to" vectors against the axis: i.e.
Vector3.SignedAngle(Vector3.ProjectOnPlane(from, Vector3.up), Vector3.ProjectOnPlane(to, Vector3.up), Vector3.up);
(A comment made using my extension on the Vector3.SignedAngle docs)
!code
π Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Vector3 originPos;
[SerializeField] bool player2Turn;
void Start() {
player2Turn = GameObject.FindGameObjectWithTag("player2turn"); // Finds the gameobject containing the script with the player2turn bool
if (!player2Turn) {
origin = GameObject.FindGameObjectWithTag("Origin");
originPos = origin.transform.position;
} else {
origin = GameObject.FindGameObjectWithTag("Origin");
originPos = origin.transform.position;
}
originPos = origin.transform.position;
GenerateGrid();
}
void GenerateGrid() {
if (!player2Turn) {
for (int x = originPos.x; x <= width; x += 3) {
for (int y = originPos.y; y <= height; y += 3) {
x_Pos = (x / 10f) - 0.15f;
y_Pos = (y / 10f) - 0.15f;
GameObject spawnedPoint = Instantiate(pointPrefab, new Vector3(x_Pos, y_Pos), Quaternion.identity, pointParent.transform); //Instantiates a new point for each loop cycle
spawnedPoint.name = $"Point {x_Pos} {y_Pos}"; //Names each tile according to their tile co-ords
}}}}
the first parameter in the for loops doesn't work, I want x and y to start from origin position's x and y properties
wdym by "doesn't work"?
red lines
"red lines" is a visual indicator that you have a compile error
originPos.x and originPos.y
you're supposed to read the error message
okay lemme check thanks
It's based on this setting, in case anyone seeks the answer
Also not really sure where you read that, as all the documentation about raycast 2D says the opposite
your right it worked. really need to make that a habit
also idk if you care but the issue was originPos.x and y needed to be converted to ints
fair enough π
Do keep in mind that it is not only expected, but an explicit rule to attempt to solve your issue yourself before asking here
Please take your time trying to research your issue BEFORE asking here next time
Not even reading an error before posting is especially egregious. It is exactly that kind of thing that is the reason these rules exist.
I think I may have been reading stuff about 3D raycasts
how is player debug/logging mode typically handled? is it fine to just create a static debug class that holds toggles for each part that all classes can call some method from
for example, i can only turn on "damage" debugging and only recieve those messages
a bool is fastest, but a better approach i know is to use channels, so instead of a bool per message type you have a channel where messages are grouped
examples are Unreal logging https://unrealcommunity.wiki/logging-lgpidy6i#custom-log-categories
and libraries like https://github.com/Semaeopus/Unity-Logger
yeah thats what I was getting at pretty much
thank you
yeah I just was focused on the code itself till now, cause i didn't think the conssole could help me like that
Value cannot be null.
Parameter name: _unity_self
Ive been getting this issue alot, how can I locate it easily?
What debugging steps have you taken. What did you find when you look it up?
ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <1885898b95cc400580ff334d9d2f9c0f>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <7aa06894fd6449a3b2bdc6ea80a8fdf4>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <7aa06894fd6449a3b2bdc6ea80a8fdf4>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.ContinueBinding (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <7aa06894fd6449a3b2bdc6ea80a8fdf4>:0)
UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation+BindingRequest.Bind (UnityEngine.UIElements.VisualElement element) (at <7aa06894fd6449a3b2bdc6ea80a8fdf4>:0)
UnityEngine.UIElements.VisualTreeBindingsUpdater.Update () (at <af5e17e7e1834739bb16ccdf35ffd3f2>:0)
UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <af5e17e7e1834739bb16ccdf35ffd3f2>:0)
UnityEngine.UIElements.Panel.UpdateBindings () (at <af5e17e7e1834739bb16ccdf35ffd3f2>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <af5e17e7e1834739bb16ccdf35ffd3f2>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <af5e17e7e1834739bb16ccdf35ffd3f2>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <7aa06894fd6449a3b2bdc6ea80a8fdf4>:0)
how do I look that up
By looking up the first 9 words without the rest of it?
im sorry ive never seen an error like that
The entire stacktrace is not from your code, so it's not your problem.
The only way to prevent it is to try not to do whatever it was that caused it. If you don't know, clear the error and move on
its crashing my game though
Crashing?
yeah your right it isnt a code issue
is that the whole stacktrace?
it randomly works
like rn it worked
after exiting unity to come on here then going back to it
Crashing would mean that the application closed, and I highly doubt that happened
I have this issue where I cant drag my text box into the spot I have on my script does anyone know how to fix this?
You are using the wrong type. If you're using TMP, that's not Text
so when I create object what do I do?
If you're using TMP, that's TMP_Text
Change the code, not the object
Thank you
I've been buggin about that forever
yeah i mean it broke out of the play test
whats the term for that
I have no idea what " broke out of the play test" means. If you mean it paused, then that's because you have error pause enabled
Unity has 2 Play Mode states, PlayMode and EditMode
you may mean you exited PlayMode
yeah
ohh lol thought that was a necessary feature
anyone know why this is formatting incorrectly?
What is "this"? Is it a console log?
Oh, so you're using an asset
I don't think it supports them by default.
Alright. Maybe reverse engineer that log to see what tags they're using.
i'm doing it lol
no reverse engineering
I think it might be an issue with it being multiline?
not sure
Try breaking it down into several lines.
Can you share the exact text that was used for the working log?
i'm trying to have it all in one message
sec
return string.Format("<b><color={0}>[{1}] </color></b> <color={2}>{3}</color>", channelColour, logChannel, priortiyColour, message);
And the one for the not working one?
thats the general form
In fact it would be better to compare them in the debugger such that you see the final form of the string and escape characters too.
so the whole string would go in {3}
<b><color=cyan>[Combat] </color></b> <color=grey>Player attacks Floating Skull, it has 0 FireResistance and takes 80 damage reduced from 80 damagePlayer attacks Floating Skull, it has 0 IceResistance and takes 39 damage reduced from 39 damagePlayer attacks Floating Skull, it has 0 LightningResistance and takes 118 damage reduced from 118 damagePlayer attacks Floating Skull, it has 0 PoisonResistance and takes 0 damage reduced from 0 damagePlayer attacks Floating Skull, it has 0 ChaosResistance and takes 110.58 damage reduced from 110.58 damagePlayer attacks Floating Skull, it has 0 PhysicalResistance and takes 414.72 damage reduced from 414.72 damage</color>
thats the full form
i removed the newlines, same issue
And have you tried just logging that as a raw string, without reconstructing it?
how should I access a gameobject in ddol
same issue, maybe its a character limit?
doesn't really matter anyway
There is no issue in my version of Unity, however cyan seems unsupported
Did you look this up?
It is exactly the same way you access an object in any scene
Basically pretend it isn't even in ddol
It's just a scene like any other
what version are you using?
6000.0.0b14
Nice
maybe thats it
im on 2022.3.14f1
im assuming thats a beta version ur using
should I update or do I risk breaking things, never updated before lol
I see no reason not to update to the latest f release for your version, as you can always roll back if you're using source control. As long as it's not changing major or minor version there shouldn't really be any meaningful changes that can break things
There's 9 releases that could have fixed the issue for you that are pretty much the same release as yours
kk thanks
hey fellas, still working on a 2d game and i need a pop up to appear with text when i get to scene i cant find any documentation about making these popups can someone help me out?
wdym by popup?
A UI popup?
Or just like... damage text or something?
need a box to pop up with a message explaining stuff
gracias