#archived-code-advanced
1 messages Β· Page 157 of 1
Write your intermediate results out to computebuffers and print them out in cpu world
yeah, might be the only way
@round pawn It's possible to debug compute shaders using tools like RenderDoc. See for example https://renderdoc.org/docs/how/how_debug_shader.html#debugging-a-compute-thread and https://docs.unity3d.com/2021.2/Documentation/Manual/RenderDocIntegration.html.
I've used that to good effect for figuring out where my compute shaders are going wrong; allows stepping forwards (and backwards) by individual statements or instructions, inspect intermediate values, etc.
Fwiw, the link Mindstyler sent earlier is basically the same thing but using Visual Studio instead of RenderDoc. It is specifically about debugging compute shaders, so you might want to have another look at that too instead of dismissing it because it has "graphics" in the title
I didn't dismiss it because of "graphics" in the title
I am repeating this process quite often, and open to ideas on how to make this more streamlined in the editor:
- Add a
TextMeshProUGUIto my scene. - Add a public variable to the (only) script in the scene with the same name.
- Link the object in the scene to the variable.
- Add a line of code in a method called LocalAssert():
Assert.IsNotNull(MyNewTextObject);
It might not always be a tmpro object, sometimes it's a button or progress bar or whatever, but the above is tedious.. would love a way to automate it or put it into an editor popup of some sort. Any ideas?
I just did the above about 400 times π
can anyone tell me why my character is unable to rotate and move to the above platform?
It will have a split second upside down animation and then back to original position on the bottom platform.
hdrp?
I'm trying to load a prefab from SteamVR in a Kerbal Space Program mod. When I included SteamVR.dll alongside my own mod DLL, it throws this error when trying to load the assetbundle:
937 [LOG 13:30:05.198] [FirstPersonKerbal] Bundle: vrplayer, Asset: assets/steamvr/interactionsystem/core/prefabs/player.prefab
938 [WRN 13:30:05.855] The script 'Valve.VR.InteractionSystem.Player' could not be instantiated!
939 [EXC 13:30:05.858] TypeLoadException: Could not load file or assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. assembly:netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 type:<unknown type> member:(null) signature:<none>
Without SteamVR.dll, the assetbundle loads but the script components are missing
Am I compiling SteamVR.dll wrong maybe?
I think KSP runs on Mono 4.something, which may be too old? How do I change the target framework for SteamVR?
Yh
Itβs a game jam submission which is ending in 10H and Unity been throwing error a lot today!
@tribal narwhal let me tell you about a feature called: Screenshotting. it's awesome
I don't know if this belongs here, if it doesn't I can move. How can I get started getting an online multiplayer environment set up?
Yh sorry
Pick a networking framework and follow their documentation/tutorials
Is there a good networking framework that you can suggest (I don't really want official servers for this one, just player based servers.)
Photon and Mirror are two popular options.
unity's networking solution
I recommend Photon Fusion
(Photon offers many different ones)
all 3rd party solutions are expensive
expensive resource wise?
no money wise
There's not going to be a free lunch
At least for now I'll have to just go with Unity's then
of course not. but rather get own servers than paying a license upgrade
I'm wanting to just use portforwarding to have my own servers.
i recommend dedicated servers
I wanted the servers to be more along the lines of how MC handles it.
minecraft are dedicated servers
Not all. Minecraft has all sorts of server styles.
all. except if you play over lan only
You can portforward your own server for MC, and pretty easily at that.
minecraft uses listen servers for singleplayer/LAN and dedicated for everything else. Unity's Netcode for GameObjects can do both and is actually super easy to get started with. I haven't personally tested it with anything super complex yet but it's pretty decent
port forwarding is also not related to the server implementation, it's something you do on your router to ensure the port the server uses is available for outside connections
Alright, well none of that even matters now because I just remembered I got a new PC
which impacts it.......how?
which version are you using
2021.2.7f1
I am trying out this solution here
But now i get some more problems!
namely this
-Its Fixed-
You're probably firing this off every frame because it's actually difficult to only press a key for just 1 frame. Use Input.GetKeyDown(KeyCode.A) and see if that works better.
This is causing your check if zAxisRotation (which is decremented by 180 every frame) is < =360 to evaluate to True within 3 frames and reset the rotation to zero. I would probably do something like zAxisRotation = Mod(zAxisRotation + 180, 360) to continually keep your rotation values within range. I haven't played with Quarternions too much but you could also probably just rotate that and let that take care of normalization of the value.
I've imported an asset called Grapher, something to help with debugging. I can't access it though because it sits outside my Scripts folder's assembly definition. I'm new to using them and still trying to get the hang of it. How should I add it to the reference? I know I can make Scripts reference it and let that trickle down access, but I figured I'd ask since this is meant to be something fairly global scope.
Put an assembly definition inside the Grapher folder, then you can reference that from your own assembly define, look under "Assembly Definition References" section of your asmdef
Arlight. For something like this though I just have to reference it at the highest level defintions where I plan to use it to make it fairly global? There's no way to give all definitions access to it by default?
Would it be possible to create a tube mesh from a certain amount of points? Like a 3d linerenderer.
Hi there
I'm trying to write to a file on Android with this
var bf = new BinaryFormatter();
var fs = File.Create($"{Application.persistentDataPath}/player.save");
bf.Serialize(fs, saveGame);
fs.Close();
but it's not working
am I missing something?
Define not working
Have you looked for the file? https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html
yes, it's not being written dunno why
afaik it's supposed to be at the path described in the API
I don't think I'm missing a permission cuz it's the data path of the app...
Anyone know how to make it so that when i create a new script through "add Component" in an object, it either puts the script in folder called Scripts, or creates a folder if there isn't one already?
any way to do that?
a very specific thing I realized
You mean when you right click in the inspector? Yeah I think it dumps it in your base Assets folder. IMO just a reminder to keep your code nicely organized
Yeah I organize it manually every time
but I figured someone might have had the same problem and figured some way to automate it
omg , thanks for noticing it. Cant believe i forgot that 4 letters "Down". Now it works
another question, transform.localEulerAngles means that it will make that object transform to the fixed angles.
What is the correct command to be use , in order to turn 90 degrees from current angle ?
in reference to gameobject's axis and not world axis
that's far from an advanced code question, but it's transform.Rotate
oh opps, didnt notice the location that i first posted my question. sorry bout that
This script draws raycasts around the center of a space ship, I'm trying to get it so that the rayRange is equal to the magnitude of velocity in the assigned direction, would anyone know a way to calculate this? I thought of using the rigidbody.velocity.magnitude * direction but that would essentially just make all rays equal to the magnitude.
for(int i = 0; i < numberOfRays; ++i){
var rotation = this.transform.rotation;
var rotationMod = Quaternion.AngleAxis((i / ((float)numberOfRays - 1)) * (angle * 4f), this.transform.forward);
var direction = rotation * rotationMod * Vector2.right;
Gizmos.DrawRay(gameObject.transform.position, direction * rayRange);
}
}```
project the velocity vector onto your direction vector and use the result to draw your ray
I'll give it a go, thanks π
Found this while replying to something on reddit. Just thought I'd drop it in here - I think its an absolute must-read if you don't know anything about CPU caches. It goes into some of the reasons why DOTS exists (or is starting to exist) but I would argue it is actually more relevant for those NOT using DOTS because the whole point of DOTS is so that you don't have to think about this....
Some surprising things like a case where an array of pointers is less efficient than an array of copys because it uses the cache more efficiently.
Just really well written:
https://gameprogrammingpatterns.com/data-locality.html
for destroyed objects I assume
(object)someGameObject == null is true?
No
not asking because I fancy that style but because I stored a GameObject as a object
hm yeah I guess it makes no sense
so best I should do (GameObject)someGameObject == false (if in this case someGameObject was stored as object) to check destruction?
great π thanks
good there is people like vertx around that make sense of everything Unity π
another question
I used to do a lot of throw new Exception(..) in the past. Cause I generally like fail fast
But specifically for unity it seems with a Debug.LogError and trying to bring the program back into a good state is often the better option
maybe someone has an opinion?
not sure what you mean exactly. for a real release you for sure never want to throw an exception
that isn't going to be caught, that is
fair enough
Debug.LogError for codes you donot want to end abruptly.
throw new Exception for something which you dont want to continue on error. try to return the code as much as possible tho
unhandled exceptions are caught by unity player loop. so it negatively affects the player loop execution
I'm eyeballing myself, why is it that the Build behaves differently than my Editor for my Behaviour Tree!! Is there someone willing to take a look at my Behaviour Tree code to help me, because I'm lost
The problem follows: In the editor the game runs fine, the AI (Chickens) behave properly. When building the game this all turns. Suddenly the Behaviour Tree used for the AI becomes very unstable, making the Chickens run into invisible walls or making them go off the NavMesh, and this only happens in the Build.
I have a list containing DIFFERENT subclasses that all derive from the same base class. When I iterate through the list, how can I tell what the subclass of each item in the list is so I can cast it properly?
You shouldn't need to do that; treat them as the base class, and as long as methods are appropriately defined, the right method will be called on them. If you have to know what subclass they are, you're doing something...well, maybe I won't say 'wrong', but definitely odd.
The methods don't pop up for the subclasses, just the base class
only "delay" shows up but each subclass has many more methods.
Which makes sense, since i am iterating through by base class
Which is the right thing to do; if there's an attribute they all should have that you're going to operate on (like target and position) they should be in the base class, and if necessary overridden by the subclasses.
I have a custom inspector and i can add any subclass I want. So when this particular action is run, it can literally be anything in there
But is there a way to figure out what the subclass of the currently selected script is?
even though i found it by base class?
This is the heart of the Liskov Substitution Principle. Don't do what you're doing; do it in a way that the method that can operate on the base class, can operate on the subclasses. Or they're not subclasses anymore.
I think i follow but can you explain more
edit: actually i get it. I can add an enum to the base class so the operator can use that to identify the subclass
...
that didnt work so i guess i didnt get it lol!
If you're figuring out what subclass it is and casting it to call specific things, you're doing it wrong. But ydy.
What is a better way to do it?
if i have a list (series in the screenshot) of various subclasses, how can i access the values in them?
a for loop?
You only operate on the common aspects of them. If you want to ask them all to do something, you implement a method, 'DoSomething()' that you can blindly call. In short, if you have a collection of the base class, you only should call methods that are defined by the base class. If you want to add functionality that is used by code that will only have the base class available, you need to add it to that base class.
So your code looked like it was trying to do something with 'position' and 'target', so those seem like things that the base class should implement.
A foreach loop preferably, followed with a switch statement with pattern matching inside of it, if you want to access members on some derived classes
Thats kind if where im at. but i dont get the pattern matching thing
The problem is i can have multiple positions and prefabs etc in one action. Those positions are for tweens and i want to add multple tweens (or sometimes none)
What happens when you create a new subclass that you don't have a case for? You miss adding it to that list, or another programmer doesn't know they have to, and you're in trouble because now it's not handled.
Sometimes it can jsut be an animation, a tween, an instantiation etc
Almost correct, you just need to do the full thing
case Whatever v:
// access 'v' here...
break;
Thats the kind of annoying part. I have to update this switch for each subclass. luckily as it stands now ive planned for 7 total
This isn't a safe design, and I'd be absolutely rejecting a code review that did it, but...here: https://stackoverflow.com/questions/298976/is-there-a-better-alternative-than-this-to-switch-on-type (specifically Zachary Yates' answer). I believe Unity supports C# 8.0 which should include that. I really, really wouldn't do it.
But as i think @coral folio pointed out, I dont think im abble to access the values of the subclasses
You are, with pattern matching you absolutely can.
But, it would be better to have a common denominator like an abstract method or property in the base class that all inherited classes implement
So you don't actually need to modify the switch statement everytime you add a new inherited class
I have an enum in the base class. Is that sufficient? (sorry for the questions. this particular thing is pushing beyond my C# knowledge)
[System.Serializable]
public class Action_Series
{
[SerializeField] public float delay;
public SubClass subClass;
public enum SubClass {
PositionTween,
Animation,
Prefab
}
}```
No, the idea is that if there's a piece of information you need from your subclasses, you express it in your base class (as an abstract function) and implement it in your subclasses to give the information, rather than having your foreach loop reach into the guts of each individual class and figure it out for itself.
Ah! that I (somewhat) understand
So the abstract is null unless that subclass fills it?
Well, the subclass must fill it in; but it can return null if it wants to.
Well, okay, you can define it virtual and then have a default implementation that returns null, for instance.
and then the subclass has to use an Override?
Here's a decent post about this that provides a pretty good example of abstract, virtual and a few other concepts: https://answers.unity.com/questions/1369097/question-about-protected-and-abstract-classes.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Here are two subclasses of "Action_Series". In the switch, i want to check if the item in the list is a "Action_PositionTween" then it runs a tween and goes to the next item in the list. The next item can be another tween or can very well be an "Action_Prefab" where it instantiates something instead, or an "Action_Animation". And there can be many of them in the list.
Is this the current way im doing it (using a switch) the best way to do this? or do you know a better way?
I didnt know you could make fields abstract or virtual. I thought that was only for methods. Thats helpful
I don't think that code does that.
oh i see, bool is the return mehtod
Return type, but yes.
@coral folio @fresh salmon
Thanks so much for your time (its 6am where i'm at). The pattern switch suggestion and link you provided i think put me in the right direction. I don't think i have it yet but it definitely gave me a start to help write it better
Seriously, if your code had ANYTHING that it was actually doing with the data, I might be able to suggest a better way, but your code is completely devoid of any details, unfortunately.
I'm in the middle of rewriting the spell system completely unfortunately. So i'm back at square one. The intention is, in each of these switches, i run a coroutine that either:
Tweens the caster (or target) to a position, runs an animation, or instantiates a prefab somewhere. It's meant to be modular, so i can add as many tweens or prefabs i want and have them all executed from this single action, using the coroutine for delay timing
If this switch actually works, you've basically solved all my problems. When i had it working before overhauling, everything after the switch worked well
and..... it does! fantastic
So...why not have a method DoYourThing so the loop goes, item.DoYourThing() and have the item itself do all its work?
Because if i include everything in the base class, i started experiencing a LOT of bloat. Every one of the items in the list contained every option even if all i wanted to do at the current moment was a single tween. And if i wanted two tweens? i needed to add two of this base class with all these empty options and then write a ton of if statements to handle the null options. And then tell it not to tween if all i want is an animation.
No...nononono.
Basically its for sanity's sake
No, you don't DO the work in the base class. You define a FUNCTION in the base class that is called DoYourThing and when you call item.DoYourThing() in the loop, the code in the subclass gets called. And it does it's work.
What I'm saying is that EVERY case within that switch is going to grab data from the item object, manipulate it, and do work. That code could be in a function in each subclass, and be magically auto-extensible, and the data and the code to manipulate that data will live together, where they should.
That's what virtual and abstract are for. π
alright! I always felt like something was wrong. I had a folder of 12 different classes just to do actions. this feels like it will be better
nodnod I think it will; unfortunately I need to wake up in 3 hours, so...I should get a little sleep. π
I imagine your loop should end up looking something like:
foreach (Action_Series item in action.series)
{
item.PerformAction();
}
Or whatever method name you end up choosing. Best of luck!
I scrolled back up and realized this is what you were telling me to do from the beginning. I just didn't get it lolol
Can anyone help me with this problem?
I'm willing to reward the person who can help me solve it, since I can't do much now
Without actual context no one can help you; thus why they've not done so.
There is context
The problem follows: In the editor the game runs fine, the AI (Chickens) behave properly. When building the game this all turns. Suddenly the Behaviour Tree used for the AI becomes very unstable, making the Chickens run into invisible walls or making them go off the NavMesh, and this only happens in the Build.
You're asking for someone to take a look at your behavior tree and not providing the actual data to be resolved; the tree. Without context not many will be charitable enough to elect themselves for volunteering to help without seeing the actual problem.
Alright, I'll provide it in a few hours
BrakeLights.materials[5] = BrakeLightsOn;
This code is not changing my Material for an element in my GameObject
. materials returns a copy of the materials array
You are only assigning an element to that copy
You need to assign your modified array back into the .materials property to actually affect the renderer
how do i simulate a click on other programs
someone told me to search low os function on google but i found nothing useful
Does anyone know of a way to get Unity VS projects to actually use nullable reference types without having to use directives in every file? Everything I find online seems to just get ignored by VS
what do you mean?
you mean the strict checking?
i.e. non-nullable reference types are what you want?
the monobehaviour model doesn't really support it. your best bet is to have a separate project and reference the assembly
not really advanced code
oof but do u think u can help π¦
Not a coding question at all...
but I am facing the problem in unity so where do I ask π¦
don't architect things this way. just write a function for every spell, and in its code, it does what it's supposed to do. use DOTween for tweening. use a coroutine to time things out.
you will have like maybe 100 spells max. even if they were complex lines of code, like 20 lines each, 2,000 lines is less than supporting a general way to define spells with the editor
yes, binary formatter isn't going to work for general unity classes
ok... do you know what would work? specifically on android
it does work on desktop though
i don't know what the issue is really. is it saving the file? is it binaryformatter? what is the exception?
is there no exception?
how do you know it's not working?
the BinaryFormatter and Filestream should create or read a file (savegame) on startup to read some values, while the file seems to be written, it fails to load back up
how do you know it fails to load?
what happens?
is there an exception?
the savegame contains some values to "continue" the game after a level, which doesnt happen on second startup (it should, it does in editor)
not that I know of
you can use is to check if an object is an instantiation of a particular class or implements an interface. Ie if(item is SpellAction) { ... } else if (item is AttackAction) { ... }
var bf = new BinaryFormatter();
var fs = File.Open(GetSaveGameFullPath(saveName), FileMode.Open);
save = (SaveGame)bf.Deserialize(fs);
fs.Close();
this is my loadup code
so save is what?
have you inspected it in the debugger?
how large is your save data? maybe just store it in playerprefs
or maybe use an asset from the asset store. this is some basic stuff
it's hard to know because you haven't really diagnosed this.
IMO this is better suited for an Interface, so that inheritance is not required.
what's the objective?
just a variable with the serialized data
yes, like I said, it works in the editor as intended, just on Android it doesnt do
just a couple hundred bytes
to make the program press buttons in other windows
what does it have to do with unity
like what's the gameplay?
just save it into playerprefs
and using JSONUtility instead
save a json string into player prefs
I'd rather not, would like to figure out why specifically this isnt working
it will work 100% in all platforms
it is better to use playerprefs whenever possible
because its the only language i know
aight I'll think about it
it's easy. just use PInvoke here are some references: https://www.pinvoke.net/default.aspx/user32/SendInput.html
The SendInput API
didnt understand a thing
like if i just wanted to make it do a right click what do i write
check the references i linked
i am not a smart guy
and there is a lot of text
and i am dumb
you'll figure it out
then lets die
and my eyes say goodbye
ah i figure it now
but i dont know what is the INPUT type(string ,int ,float ...)
look at the sample code. StructLib.INPUT()
My BehaviourTree:
My problem is above the comment I answered
you gotta stick to unity stuff or a mod will have to visit this thread
figured it out, code works just fine, it was just my timing when I saved that accidentally resetted the save
thanks @undone coral
Is this for me?
no. i replied to someone. look above. the original message was deleted
That's why I was confused π
now i copied everything and didnt know how to call the functionπ
i have tried coping the sample code and what i got is a lot of errors
you call the method the same way you call any method in c#
but what do i write i copied around 950 lines
and i dont know any thing about how they work and i am lost
I want to mesh triangulate this area with given points(the white points on the screen) in 3d space
what should I do ?
you can try this https://assetstore.unity.com/packages/tools/modeling/realtime-csg-69542 you'd model the two curves separately then bridge them
https://www.codeproject.com/Articles/5264831/How-to-Send-Inputs-using-Csharp
i found this website and its better
it is using the exact same PInvoke
i ment better at explaining
sure. it still uses the same code though
Hello, I have a lil scheme with an issue i've been struggeling for for like the past 4 months and i'd like to know if there is anyone that could give me some tips or tricks or maybe give me some help
This is the struggle for me
can you be more specific what the issue is?
@rapid sky I think what you're confronting is how to model categories in code. How I interpret your 'same script' question for the weapons and the enemies is you gesturing at a desire to deal with enemies in a generic way, and separately to deal with player weapons in a generic way.
When I model categories of things in my code, I usually model it using an 'abstract interface' modeling technique. Sometimes I model it using a base class, other times I use an interface, and still other times I use an abstract class.
The challenge is figuring out what the common elements are across a category of thing. For example, a player weapon needs to be able to fire. No matter the type of player weapon, it will have to conform to that interface. The details of what it means to fire is specific to the abstract interface implementer
Same thing for the enemy -- you want to have multiple types of enemies but handle dealing with enemies in a generic way.
Rereading the diagram, I think what you're after too is defining how the weapons systems interact with the enemies. Most of the time, the player weapons are interacting with a health system.
they are
Let me know if this is off base, I'm making some guesses
nono you are in the right direction
wait ill get something of pastebin
this is what defines the interaction between the bullet and the enemy
Nice.
public class Health
{
private float MaxHealth { get; }
public float CurrentHealth { get; private set; }
public Health(float maxHealth)
{
MaxHealth = maxHealth;
CurrentHealth = MaxHealth;
}
public void ReceiveDamage(float damage)
{
CurrentHealth = Mathf.Clamp(CurrentHealth - damage, 0, MaxHealth);
}
}
public abstract class Ammunition
{
public abstract void DecreaseAmmo();
public abstract bool Empty();
public abstract float Damage();
public abstract void Projectile(GameObject agent);
public void DealDamage(Health healthSystem) =>
healthSystem.ReceiveDamage(Damage());
}
public class PistolRounds: Ammunition
{
private int _rounds;
public PistolRounds(int rounds) => _rounds = rounds;
public override void DecreaseAmmo() => _rounds--;
public override bool Empty() => _rounds <= 0;
public override float Damage() => 35;
public override void Projectile(GameObject agent)
{
// use agent position to fire straight
// ...
DecreaseAmmo();
}
}
public class Weapon
{
private readonly Ammunition _ammo;
private readonly GameObject _agent;
public Weapon(Ammunition ammo, GameObject agent)
{
_ammo = ammo;
_agent = agent;
}
public void Fire()
{
// default implementation that can be overridden
if (!_ammo.Empty()) _ammo.Projectile(_agent);
}
}
public class CombatTests
{
[Test]
public void WeaponCanFire()
{
var agent = new GameObject();
var ammo = new PistolRounds(1);
var sut = new Weapon(ammo, agent);
sut.Fire();
Assert.IsTrue(ammo.Empty());
}
[Test]
public void AmmoCapableOfDealingDamageToHealthSystem()
{
var sut = new PistolRounds(1);
var enemyHealth = new Health(100);
sut.DealDamage(enemyHealth);
Assert.AreEqual(65, enemyHealth.CurrentHealth);
}
}
@rapid sky Not sure if this helps you, but here is an example of trying to model out commonality in game elements using what I was talking about earlier.
ill try it out tomorrow
thanks alot for trying to help me
i want to get this fixed soo bad so i can finally finish my first version of the game
Some advice: if you found yourself stuck for many months on something, ask yourself if you are still on track with your goals. Itβs good to throw yourself at something difficult for your experience level because it helps you understand more.
But if you are trying to release something ASAP or something you may want to consider another strategy. You know you bestβ Iβm just offering an opportunity to reflect!
anyone with expiernce with photon hastables can help me with my code
trying to have a number get set to 1 when the client i want to create the room starts and players join the room when that number is 1
if its not 1 then the room isnt created and people cant join
trying to make a check and not having much luck with it
works perfectly find if its just else but i need a condition so it doesnt work if i dont connect first
else if (photonnetwork.playerlist.length>=1) doesnt even work
Anyone down to call?
size of one table affects speed of pathfinding, despite not being connected
Do not cross-post.
?
Cross-posting, the action of posting the exact same thing across multiple channels to attract more attention.
So my problem is
Before you continue, this is a channel for advanced code questions
Make sure yours fits that channel.
I made a enemy script which attacks the player health when the enemy stands next to the player now i did a health ui and i wanna assign the damage function which the enemy does to the healthui script
But how
Just call a TakeDamage method on the player's controller script whenever the enemy considers it having hit the player. It can pass it's own damage amount and the player can handle the results.
hey so I was making a trigger so when it enables it makes the canvas active but it is not making it active
using UnityEngine;
public class showquestion : MonoBehaviour
{
public GameObject OurQuestion;
void OnTriggerEnter()
{
OurQuestion.SetActive(true);
}
}
Verify your trigger is calling?
kk lemme try
Then follow the guide pinned to #π»βcode-beginner
Well, there's your issue.
The correct channel to be asking such questions in
Hello!
I have a line renderer and I use it to draw things on 2D scene that disappear after a few seconds.
I want to introduce a βresourceβ which will deplete as I draw. E.g. it starts at 100 and it goes down to 0 as you draw. Then I also want this resource to increase passively (+X each Y seconds) and to have a pick-up that grants some resource immediately.
Iβm quite new to line renderer, so Iβm not sure how to approach this. Should it even be tied to Line-renderer dots or no?
Any advice is appreciated!
Here are the 2 scripts i'm using:
DrawManager - https://pastebin.com/pPGBVX4s
Line - https://pastebin.com/Ja8A8CFx
p.s. scripts are taken from a tutorial
Hello, is possible to make in c# a main function and then when i want to add code to it dynamic? like ```c
public void mainFunc()
{
.....
if(..)
{
here i want to add code dynamic
}
}
and then to have smething like
mainFunc({
GameObject.SetActive(false); or something idk
});``` sorry if i gave a bad example but idk how to really express about this
Looking to do something beyond strategy pattern?
its best if you explain the purpose, then we can provide proper solutions to the problem
i don't know exactly if i want to do that, i have a Database manager in my game and everytime i need a new thing related to the database, i need to write the same thing over and over just to add some conditions like in my code from above, like to have a code pattern with all the stuff and then just add some conditions, debugs etc
example of "the thing related to database" ?
You want main func to accept parameters.. e.g MainFunc(bool state, int somevalue) so you can make it reusable
i have this: IEnumerator CheckUsername() { string post_url = (URL); UnityWebRequest hs_post = UnityWebRequest.Get(post_url); yield return hs_post.SendWebRequest(); if (hs_post.error != null) Debug.Log("[DB] There was an error: " + hs_post.error); else { string dbResponse = hs_post.downloadHandler.text; -> } } every time i want to check a new thing or get informations from the database i have to copy that chunk of code and just add my if's or logs under dbResponse and i want to see if it is possible to make a function out of that and just add conditions down there without copy all the code again. i doesn't really know how to explain this
IEnumerator CheckUsername(Action callback)
{
....
if(error)
...
else
callback?.Invoke();
}
StartCoroutine(CheckUsername( ()=> Debug.Log("Success"));
something like this?
yea, something like that
you should wrap your queries tbh
DatabaseUtility.Request(string url, Action<object> onSuccess)
I'm trying to find out how to create a polygon using code, apply a texture to that polygon, and add a 2d collider to it, but I can't find any information on it. I did this a couple years ago so i know it's possible but I can't find any information on how to do it.
My goal is is to slice a texture that will act as a TileMap, and then create a 2d mesh with collisions to act as terrain
new Mesh()
mesh.SetVertices() and others is probably what you need
Can I add a 2d collider to a mesh like that? I know the MeshCollider component does not work in 2d, and I don't know how to add 2D colliders
just add a 2d collider
As a test I tried to add a 2d collider to a plane and it just gives me an error
you can perfectly fine add a 2d collider to a plane
How does 'Wait Until' work?
yield return new WaitUntil(() => loadedPrefab != null);
In a coroutine, does it pause the coroutine until loadedPrefab is no longer null, or does the coroutine need to be run again?
the coroutine is paused, and the method you passed to WaitUntil is called at most every frame
I think instead of creatimg my own mesh I'll try and create a script that can manipulate Unity's built in TileMap
unity already creates colliders for tiles and sprites
oh... you have to pass a method? I can't just pass a bool?
because of the lamda?
it's a lambda expression
it's a piece of code
it will get executed every frame at most
What if i just did
yield return new WaitUntil(loadedPrefab != null);
Thats the part i dont udnerstand
that's what i thought
I am getting an error
AH! i need a function that returns the value. THank you
hmm
yeah you do
but a lambda expression, a method and a function are all sort of the same thing
yield return new WaitUntil(loadedPrefab != null); is a syntax error
it's telling you that
the way wait until works is
- pause the coroutine
- call the thing you pass it at most once a frame
- if that thing returns true, resume the coroutine
() => false
() => { return false; }
are the same, and might be more illuminating to you about what's going on
() => false and false are totally different
That right there is the key
I dont get why those are different
is ()=> essentially a function?
Gotcha. That makes much more sense now
thank you. that was good
he is good, love the guy
Is there any solid reference on what I can do with Jobs on background threads and what has to be done on the main thread? I know I have to Schedule() on the main thread, but can I IsCompleted() or ScheduleBatchedJobs from the background?
everything that touches something that extends Unity.Object that doesn't have its own Dispose method i think
it isn't well documented no
Well yes, but none of those methods have anything to do with the scene/Unity Objects
you can just try and see if you get an error
yeah you sort of have to try
i don't see why iscompleted can't be called from anywhere, although the answer might be transiently wrong
I mean sure.... but I'm asking if anyone knows or if its documented....
not yet
... i doubt no ones ever figured this out lol
what are you trying to do with Jobs
That's a very detailed and long answer that's not really relevant
okay i might be able to offer a simpler solution
that performs as well
not as an alternatiev to jobs
but for example, why you'd want to call a unity job from a different C# thread, or how you're expressing dependencies between jobs
i think the jobs api is thread safe
maybe just a brief answer?
I'm not looking for architectural advice - I know how to architect code. I need to perform a lot of jobs and the divvying up of tasks into jobs needs to be background threaded on it's own. I just need to know if I can safely check their completion and such tehre as well or if I need to keep posting back to the main thread. A simple "yes" "no" or "i don't know" is totally fine. But I'll take the latter and get to writing my own tests since no one here atm seems to know
sounds like you need help architecting code
hard to know though without knowing what you're trying to do
he's talking about the unity job system
yeah as a means to an end
wonder what it could be
That's entirely irrelevant and extremely pedantic of you to assume I need help architecting code
I asked a simple question about a single API, not your advice on software design
okay i can confirm it's thread safe
nah usually the people who don't say what they're trying to do
almost always make a mistake
That's still not my question. One would hope multithreading apis are thread safe
just jumped in, but short answer is, you have to keep checking from the main thread if the job done.
it's documented in the source
Link?
jobs needs to be background threaded on it's own
Jobs itself can't be scheduled in a background, it has to be mainthread
ScheduleBatchedJobs also is thread safe
divvying up of tasks into jobs needs to be background threaded on it's own. was the full quote. I know they have to be scheduled ont he main thread
now will you say what it is you're trying to do?
No.
it will help to express it in like a sentence
c'mon just a little hint
it's voxels?
you're trying to raymarch voxels blah blah
generating terrain meshes?
Again, I don't need architectural advice. Especially from someone just throwing around buzzwords. Thanks for the link.
what are you procedurally generating?
looks like levels for a platformer?
looks like a multiplayer environment of some kind
hopefully you're not reimplementing navmesh
@undone coral can you just stop
And now you're spamming/harassing about it.
@bright wind btw there's #archived-dots for dots questions specifically
Reading this exchange is very lolβ¦
Well, I wouldnβt say thatβ¦ we are all trying our best.
in general trying to procgen meshes works poorly
there are so many existing assets to achieve this
stop throwing out misinformation. procgen is super easy and nice with jobs
a) what does that have to do with anything and b) no, that's not really true, it just attracts a lot of people who dont know what they're doing
i'm saying that individuals trying to stitch together vertices and make a mesh that looks good
from scratch
it's hard
I asked a simple questiona bout the job system and youre off on a tirade about proc gen
i really like mudbun
no. it's just as easy as if you'd do it without jobs
i'm advocating to use existing asset store libraries* for most gameplay scenarios you want to generate meshes and find yourself trying to author that from scratch
Why are we talking about generating meshes?
what are you even on about? most libraries are worse than writing from scratch
This is a channel for coding questions, not library advocacy
This is entirely off topic
the mudbun asset is extremely well written
so is realtime CSG
at least in these specific cases
of procedural generation
whatever
it's about redefining what your gameplay problem is
no
well i can recall one user - maybe it's even you - who made a very very pretty planet generation
no
there are definitely exceptions
it is really hard to make something that looks good is all
it's not realistic for a single person without a pre-existing graphics background
it's like trying to be a Pixar Technical Director while also writing a game
just stop no one cares anymore. move on
you'll wind up making something very retro
mudbun is really excellent for procedurally generated bipeds and the like
like if you wanna make rigged characters
it might be the only game in town
I think he's getting a rise out of keeping this tirade going. It's so far gone from the original question. Think it's time to just ignore him and move on
there's some really amazing stuff made with it
great. use it. no one cares. not relevant here anymore
true
@bright wind I should probably ask later (since the conversation heat seems to be unfortunately up) but⦠First, can I say I like your avatar? Cats in pictures are always fun.
Second, and this is just me being a curious programmer. What is your use case for using background jobs in unity? Iβve used the technique in my software engineering work for bigcorp quite a few times but I havenβt really found a use case in Unity. I know you may be busy but I would love to read what you write. I agree it isnβt relevant to your question but, just me being a curious programmer.
i also can see how, if you come from a software engineering background, if you are developing games for the first time, unity can be really frustrating. there's a lot of stuff that doesn't matter much in game development, like package management and tests and c# language features, but matters a lot in app development or whatever people use C# besides this nowadays.
Again, entirely off topic to my original question. Plus I've been doing game dev for 10 years. And no real serious app development uses C#. Move on dude.
This isn't your soap box
and people coming from those backgrounds will feel frustrated. especially a web development background, where libraries can be bad but also you don't pay for any of them, or from a backend engineering background, where a lot of stuff is generally engineered better than in games. this is all okay
Could be anything heavy that you don't mind waiting multiple frames or even seconds for, generating chunks in a minecraft style game would be a perfect fit, for example. But it can also be pathfinding, ai logic, terrain destruction etc etc
are you even listening ? stop chatting here about irrelevant stuff and put your thoughts somewhere. Oh, I don't know #π»βunity-talk . At least someone there will listen to you.
you can also use it when you need to move tons of transforms too. like marching cubes/capsules.
Marching capsules? This is what i find lol
lol
the mudbun source is a great example of backgrounding using compute shaders, it doesn't use jobs
in unity packages they use it really well for something like Sprite Shape 2D
since UnityWebRequest backgrounds for you, a lot of the stuff you'd see in normal apps you wouldn't need to do in unity
since most normal apps, their background work is waiting for a web response (IO)
is this guy actually a mudbun bot?
if you were creating some kind of diablo-style game with procedurally generated dungeons, laying out a dungeon could benefit from parallelization. on the other hand, dungeons that are gameplay-fun tend to follow simple enough rules that generating them is pretty fast on a single thread. it's hard to say if it matters, the difference in time. meshing a whole world is something that is pretty challenging, and yes would be an appropriate background task, but you won't necessarily do that much in untiy
should we push the big orange button (mods)?
i think i'm answering the question here
it would be interesting to see what a game like No Man's Sky does. the toughest thing is translating a nice looking approach, which can be serial by design, into something that can be parallelized
for example, most dungeon generation is not parallelizable, it is serial by design. but it also looks good
marching cubes are one of the voxelization approaches that are paralellizable
Two independent dungeons can easily generate in parallell
yeah so it's pretty specific
It all depends on the use case
marching cubes are exciting because they look good though
https://ephtracy.github.io/index.html?page=magicacsg < - this kind of graphics is easily procedural in ways that matter
MagicaVoxel Official Website
like composing a bunch of primitives in booleans
is a good design language for normal people, and is easy to parameterize
and turning 3d shapes in an abstract sense into a smooth mesh is possible with marching cubes
in real time
that's why people are so excited
whereas go straight from some kind of design thinking to vertices is much harder
you'd have to simultaneously figure out how to turn your idea into a mesh, and then also make it parallel
what is going on
doesnt look like it
doing something like magica voxel in real time
it's a really cool program
making libraries
that's where you'll see it
Jobs are generally for stuff you don't need in realtime though
hmm. but look where it's used in unity libraries
sprite shape 2d => for the best performance, to make realtime lines. it's true you will generally not want to do that, but that's the point
physics => realtime
usually to make procedural graphics generation fast enough to be realtime
otherwise you'd use another tool. you'd just use Maya or whatever
I asked the question, and as I've said like 4 times, you're no where near my question at all. You're not answering any question. You're just ranting.
you'd bake it. if your goal wasn't realtime/runtime, you could get it from a backend and use a purpose-built tool
I installed the input system in unity cuz I wanted to add controller support but i changed my mind.So i uninstalled it and now I cant move at all can someone help?
i see it in realtime animation libraries too
realtime fluids
and stuff by the very talented Keijiro, who makes realtime VFX art
i am verbatim deep searching github repos for using UnityEngine.Jobs
i see it used exactly zero times to wait on IO
and if you mean, like minecraft style games
I don't doubt people use it as a quick and dirty way to do something on another thread
i think those have already been solved a while go conventionally
hmm
well what would they do? make a web request? this is what i mean
im just trying to explain the real evidence, which is actual searchable code that reference Jobs
it's a good thought though
Heavy tasks where you don't care about timing
like what though
Like chunk generation in minecraft
that's all?
You don't care if its done in 1 or 100 frames
As long as it gets done
For realtime stuff, timing does matter
And as such it is not ideal for jobs
minecraft predates Jobs. but all we're really saying is that, minecraft isn't that interesting to clone anymore, so of course there aren't going to be that many libraries trying to do it performantly π
hmm... it just doesn't line up with how real code uses it
i think maybe because you use jobs and burst together, and it has a very good way to interact with native memory like meshes and textures
it appears in realtime everywhere
you can even just turn on profiler and see it
used by unity packages*, in realtime cases
across multiple backgorund workers
if you dont' care about timing, you wouldn't bother right?
would anyone care about chunk generation if not for minecraft? it's pretty hideous. does it appear in many 3d games? there's terraria in 2d sure, but you don't need to parallelize manipulating the tilemap
anyway just something to think about
i don't think anyone uses it for quick and dirty background
you're missing the point of using Jobs.
Jobs is used to process large amounts of data.
Marching cubes for example.
If you want to move 10000 cubes, on main thread that's going to tank performance.
however with jobs, you can offset that to another job thread and leave your main thread open for other stuff.
A* pathfinding is another. And since we're on the topic of libraries that you keep talking about.
the beta for A* Pathfinding Project asset are in the midst of digging into the job system to offset calculating the path.
If something takes more than a few milliseconds, you need to run it on another thread or you will block the game loop
yeah those are for realtime examples, we agree here
like pathfinding is interesting in real time
it's a great example
you still want it to finish in a few millisceonds, that's yoru goal
you're using the framework to parallelize it
marching cubes -> a graphics approach
you wouldn't try to parallelize directly meshing some terrain generation
meaning, people do stuff on here all the time
where they like, drop physics objects and make raycasts
to generate terrain
or whatever
i'm trying to answer the question why you don't see jobs used more
yeah
or any background threading
You don't see them used more because you don't see the code of the big scale games
because while those approaches are low tech, they can look good
iv'e seen the code of big scale games
graphics effects reign supreme. nowadays for things like realtime volumes
lighting
etc.
animation
anyway, how many big scale games are made in unity?
hearthstone predates jobs
biggest reason being is that most of the unity API are meant to be single threaded and thus incompatible with jobs.
which limits the scope of the job system at the surface level.
Cities skylines, for exampke
and then a ton of mobile and switch games
yeah
that's a really good example
they want their simulations to be real time right?
Cities Skylines, Dyson Sphere Program, Ultimate Epic Battle Simulator for example
Realtime = within the same frame
"Realtime" = within reasonable time
Lets just say you wanna blow a building up with proper physics and bits flying everywhere
Perhaps you dont actually need that in realtime
Perhaps it doesnt matter if theres a 500ms delay
Where its all calculated in a job
Ok, I know its been a minute since I got on here.. Im having issues with shooting a raycast a certain distance.
you're gonna have to give more info than that π
Physics.Raycast(origin, direction, distance, mask, ...)
Make sure your call complies to the following overload
its not letting me post code.
does anyone have experience with photon here? i have a question about code-generating GOs with PV
If people read the channel literally named #854851968446365696 they'd be able to post code that doesn't get munched
And post in the appropriate channel also. Not sure raycast distance issues fit #archived-code-advanced ...
Next up, what actually is the issue
@shadow seal Sorry still new here.
protip, you can use transform.forward instead of transform.TransformDirection(Vector3.forward)
@fresh salmon I want to cast only so far. The current code casts just fine, however, it travels infinite.
Well, you're passing Mathf.Infinity as the distance
^^
Of course it does
@simple badge Appreciate it!
so then something like Mathf.lightDistance, and setting float lightDistance to say 5f?
A constant is fine if you don't plan on changing it frequently
@simple badge i appreciate it! I've never worked with RayCast before.
@fresh salmon No, it stays the same throughout gameplay
Ok, do I dropped 5f in Mathf.5f and its errored calling for a " ,".
hmm
Why prefixing with Mathf
Just pass 5f
Mathf is a type, like int or string
Raycast(origin, direction, out hit, 5f, mask) for example
Mathf is a class, not a type
Mathf is a struct
Brainfart, don't know why I didnt even think about that.
Mathf is a library
Hi everyone
I want to screen capture frames...without having the camera render a scene.
Is this possible ?
My goal is to make 2000+ gifs programmatically
but I don't want to sit and wait on the animation time
have a look at rendertextures
It's a struct, and a type. All classes and structs are types. Whether they can be instantiated or not
Ill check it out
i used them quite some time ago to render different skin patterns
use this method to manually render a frame: https://docs.unity3d.com/ScriptReference/Camera.Render.html
Marching cubes! (in captain america) I get that reference (https://www.youtube.com/watch?v=M3iI2l0ltbE)
I haven't had a need to move tons of transforms in a performance way... But that's mostly because there aren't too many game entities in my games usually (1-3 dozen at most). I... now kinda want to do something that involves hundreds of entities.
Thanks for the response here, as well.
how do i make my program look at other windows like getting pixels and so on ?, i know i should search up in pinvoke but i dont know what to search in there
sounds like something we're not supposed to discuss on this server
y?
Is there a way to make Pixel Perfect Camera with Upscale Render Texture true NOT snap the camera to a grid, only the sprites? The problem with that is that camera movement becomes jittery.
Alternative question: Is there some way for a Camera's rect/pixelRect/Viewport Rect to have values outside the true screen? Unfortunately whenever I try to set the viewport to cover an area bigger than the screen, it gets clamped to the just screen.
Traditionally without an engine, I'd render the scene to a render texture that's 1 pixel bigger than the reference resolution, and draw it upscaled onto the screen with an offset depending on the camera's sub-pixel position. That seems to be impossible in Unity since trying to draw outside the screen results in squishing the texture to fit in the screen.
you're rendering to a render texture
so the screen resolution does not matter
make the render texture "1px bigger" if that is your desired solution
I'm trying to render that texture back to the screen, upscaled. That's where my issue is.
that'd be a quad and an ortho camera
Hm I hadn't considered creating a quad with the texture and rendering again. I'll try that out.
I am trying to replace pixels in a reflection probe texture and keep getting Texture rectangle is out of bounds (128 + 128 > 128) when trying to do GetPixels. Anyone know why that might be?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
If you texture is 128x128, lines 9 and 12 are wrong
then line 12 is wrong, and I'd expect that error to be from SetPixels and not GetPixels
no sorry, line 9 is the wrong one after all
your texture is only 128 pixels tall, so a rect of (0, 128, 128, 128) will fail
So this is the idea. I am trying to get the first 128x128 square of the reflection probe, and swap it with the second 128x128 square.
I get the same error if line 9 is Color[] samplePixelsuX = oldFrostedTex.GetPixels(128, 0, 128, 128, 0);
I am trying it as a Cubemap and not a Texture2D, but now I run into another issue: I cannot use EncodeToEXR with a Cubemap.
I have 2 C# scripts I am trying to package as DLLs to share. The issue is, one of those files is a ScriptableObject. Though I am extending it, it seems when you build the DLL.. somehow the script is still a mono script?
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace My_Namespace
{
[CreateAssetMenu(menuName = "ThermalMaterial")]
public class ThermalMaterial : ScriptableObject
{
public string materialName;
...
}
When I build the DLL and import it, you can see the two classes. (image 1)
However, if I click on the one script that is a scriptable object, (image 2) you can see it shows as "mono script"
I am also getting this error from the console:
CreateAssetMenu attribute on Thermal_Body_For_Unity.ThermalMaterial will be ignored as My_Namespace.ThermalMaterial is not derived from ScriptableObject.
UnityEditor.AttributeHelper:ExtractCreateAssetMenuItems (System.Reflection.Assembly)
Is it maybe not possible to do this?
@long ivy this is the updated code using cubemaps, and I am having to convert the cubemap to a Texture2D to encode it as an EXR. But it is not working and all the faces end up blank. https://pastebin.com/UiRHddmx
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
if that's your exact code, that would be the result I'd expect. Your ToCubeMap method doesn't copy any data into the cubemap
is it possible to do something like GetContacts from a trigger?
the docs explicitly say triggers don't have GetContacts but is there a way to hack it?
err this might not be advanced, moving to #archived-code-general
Yea. i "hacked" it a while ago. let me look at what i did.
Vector3 closestPointToTrigger = other.ClosestPoint(transform.position);
That
doesn't work for shapes though, only points... so you may have to do multiple ones and interpolate your shape manually which isn't too hard for simple ones (circle, box)
since triggers are essentially "volumes" there is no direct contact point
but they made a handy dandy function to atleast approximate it on the edge.
im having trouble with my code i added a weapn sway so it moves smooth but my weapon it complete stil (code https://gdl.space/polojuyago.cs )
Call βUpdateSwayβ in the monobehaviorβs Update method
sorry might sound stupid but where exactly?
got it
thanks
added this
thats wat i add
Yay! I'm glad it works. I apologize for not being clearer earlier; I think I'll call out explicitly when I'm talking about unity monobehaviour life cycle methods in the future. Thanks for the opportunity to improve!
Not sure if you have seen this manual page yet but it has a really cool diagram that explains different types of lifecycle methods and when they are called by the engine. https://docs.unity3d.com/Manual/ExecutionOrder.html If you haven't seen it before it may inspire you while you are making your awesome game.
In fact, I'm re-reading it myself. So clutch. So fire
neat, ty
less than ideal but I don't think unity provides an ideal solution here
So, I have a bunch of particles in my Resources folder. Instead of instantiating them as I need them, I'm instantiating them all at the beginning of a scene and putting them inside of a List<ParticleSystem>, the idea is to instantiate a duplicate of the existing item in the list as a way to reduce the frame drop of loading from resources every time I instantiate a new particle I need, each particle also cleans itself up, so i'm not worried about GC.
What is confusing me though, is this function I have keeps returning 2 of my particles for some reason
public ParticleSystem InstantiateParticle(string name)
{
// this searches for and returns a particle if found
for (int i = 0; i < particles.Count; i++)
{
if (name == particles[i].name)
{
ParticleSystem particle = Instantiate(particles[i]);
particle.transform.gameObject.AddComponent<selfDestruct>();
return particle;
}
}
return null;
}```
What am I not seeing here? I double verified that there's only one instance of each particle system in the list "particles" it's pulling from
if (Input.GetKeyDown(KeyCode.P))
{
ParticleSystem p = particleManager.instance.InstantiateParticle("Spit");
p.transform.position = Camera.main.transform.position;
}
This is how I am testing it, and it returns 2 particle systems every single time, and I'm stumped
i think you may need to look into pooling. this is what you are doing however. you are instantiating them and putting into list and then instantiating them again, which is the wrong way and possibly still adding to GC... once in the list just move that one where it needs to go and enable it, then disable it. put back into list for use later. Look up polling. im sure there are tons of yt videos on how to implemet it correctly.
Using pools is if you only need one type of object from the list at a time and many duplicates of same object. But im sure you could convert the basic polling into what you need. sounds like a list of different objects need to be pooled somehow. If you only need them instantiated at start to keep GC and loading times down at gameplay. And only ever show one particle effect at a time. then it should still work.
so in your code just do this. dont instatiate a new one. move the one in the list and enable it. play it. then disable it. done.
maybe change name to PlayParticleEffect(string name, Vector 3 position) and have it handle enabling playing and disabling.
One more suggestion to add to the above message is that you should avoid resources for things like this.
Resource is meant for assets which are meant to be loaded on demand. If you're instantiating them at beginning itself, it will add some initial startup overhead.
For things like this, it's best to have a Startup scene with direct reference to all assets you need on a DDOL manager for each category. Like a ParticleManager script on the init scene with all reference to the assets which you can Instantiate at runtime.
Or look for addressable system, it's the best solution for problems like this imho.
Thanks for both of your suggestions, I'll look into all of it, much appreciated
Just to clarify on this point, are you saying that it's less expensive to have a startup scene that injects a DDOL manager that, say, holds a serialized reference to a particle system prefab? Will unity still hold a reference to that prefab if I build the game and it's not in my resources folder?
And can I instantiate those from the manager as I please with less overhead than just instantiating from the resources folder?
technically yes. resources folder initialisation has additional overhead aswell when comparing it against with scene load because scene loading can make use of streaming resources which can load heavier textures and meshes aswell without noticeable frame drops (uses Unity's Async Upload Pipeline aka AUP)
Makes sense, okay, awesome. Thanks a ton
I'm not sure about the My_Namespace.ThermalMaterial is not derived from ScriptableObject. error, but MonoScript is the editor type for any C# script asset so that's not surprising: https://docs.unity3d.com/ScriptReference/MonoScript.html
See this example of a script that is a .cs file in my project:
Are you using the DLL because you want to hide your source? If you're happy for the source to be shared I'd recommend using UPM packages for this. Someone with experience of DLLs may have the answer you want though.
What you have here is a slower version of what Resources.Load actually does already.
AFAIK
Epic
Ya not too worried about shared source, just trying to package neatly. UPM packages hu? I'll give that a look. Ty!
Oh, definitely use UPM then.
You can serve your package through your git repo.
Fantastic
You can look up any package here as a reference: https://openupm.com/ @tardy loom
But it's also possible to use a private repo if you don't wan to make it public
As an example... I just made a package that has my company logo (including assets and code).
In my manifest.json I add this line:
"com.effortstar.effort-star-logo": "ssh://git@github.com/EffortStar/effort-star-logo-unity.git#v1.0.0",
Super neat. I'm just hoping to put a donate button or something similar
That's a private repo
If you want to make it public you should 100% be using UPM. It's trivial to add your package to openupm too
If you want donations I recommend adding the link to your README, but you can also be a little obnoxious and log out a request for donations when the package imports or after a project build
I know ink-unity-integration says "good luck with your release!" after you build.
You could use a build pipeline hook to do that.
You can also include assets in upm packages, not just code.
Including example scenes that can be optionally imported via the package manager
Oh I don't even want to annoy people like that. I'm cool with just if they do they do kind of thing lol
Including assets is perfect, because of the scriptable object, I actually need to do that
Yeah, exactly.
Siiiick
So when you're developing your package you'll want to add it as a local file system dependency
Ty so much πββοΈ
You can do this via window > package manager
That way you can edit the files as if they're in your project
I'm making, or have made, a thermal physics engine for unity. I'm fairly excited about it
For a cooking demo
But then when you're done just push it up to its repo. If you add it to OpenUPM and add a tag it will automatically create a release
I have virtually cooked a steak to perfect doneness π
DM me if you have any issues with UPM, I've done a few packages
Sounds delicious. Just need a 3D printer
I will! Ty!
im having some trouble with finding the problem Code = https://gdl.space/azivoworuz.cs
the error tells you the line where theres a problem
one of those references is null
t_anchor, t_state_hip, or loadout[currentIndex] is null
try logging them all to find out which one
how to i log?
Debug.Log
Debug.Log(t_anchor) etc
thanks
hello I need help with a bug. One of my arrays changes values mysteriously, when a Debug.Log in my script suggests that the script happens only a few times in comparison to the many changes to the array in inspector
The array only has one mention of it.
top one (Ancher) but how do i fix it
You're using a hard-coded string reference on line 50 to assign t_anchor. This can be pretty fragile. Looks like that assignment is not doing what you expect. Is there a Transform case-sensitively named "Root"?
I imagine you're calling Aim fairly frequently? I would recommend not calling Transform.Find in rapid succession, it seems unnecessary and (slightly) inefficient.
Why not assign t_anchor and those other references once every time the player changes weapons?
there a Transform case-sensitively named "Root"? NO
calling it twice
i now have these errors https://gdl.space/guwolihicu.cs
same way of debugging
is there any way of outputting to a tmp from outside the context of a method
like from inside but without having it be passed in
do you mean another script with the same names?
Like in a method in a class that Iβve linked the game object to through unity, Iβd like to print text to the game object without it being passed as an argument
no dont have that i think im not sure following a turtorial atm
should i send video?
Im still confused at your problem. You have a reference to a text field right? You want a method in the same class that has the public reference to change the value of the text ? What exactly is the problem
Hello, I have had a bug for months, and I was wondering if someone was capable of helping me fix it. Is anyone up for it?
Iβd accept a video
Wow broh, Welton teaches us how to make our gun aim in - nice...
(JOIN OUR DISCORD FOR A DOPE COMMUNITY, INFO, AND HELP: https://discord.gg/vrErfxa)
(CATCH UP ON OUR GITHUB: https://github.com/Kawaiisun/SimpleHostile)
Over the course of the next couple weeks, Welton will be teaching us how to make our very own first person shooter which will in...
Dont ask to ask just poste your bug and relevant code
im kinda new so i dont really know what you mean im sorry
I was talking to KeyLocker
Next time, don't cross-post. Thanks.
apologies thanks for your response also
oh sorry this is for me?
Yes
more info?
Like I said why can you do
{
myTextVariable.text="cool";
}```
No the public or private method does not matter
so yeah it dont work
Do you have more than one instance of the script in the scene where the reference is not set up
what type is myTextVariable.text?
Like a tmprogui or what ever why does that matter in the example ?
oh i thought that was question of you
@KeyLocker shit Im on my phone and typed cant for some reason. You can do like what I showed in the example
what's the error
Nre
object reference not linked to an instance or whatever
then there is no instance associated with that field
i have whats in that example
But does every instance of the script has its text field filled?
Like in a method in a class that Iβve linked the game object to through unity, Iβd like to print text to the game object without it being passed as an argument
is what i posted before
Cause this would be the only explanation
Try do write t: ComPonentName where this is the name of the class and see how many components you have in the scene
On every instance of the component in the scene ?
theres only one instance
it works without this
like
it works
i just want it to work without it being passed as an argument
And Im tellin you it doesnt need to be a argument
Try the t:ComponentName in the hierarchy search bar to see if there is only one instance of the component
Design tip, streams are disposable, so use a using statement to properly dispose of the stream whatever happens. Unclosed streams may cause issues later on, especially when a dangling stream locks access to a file, preventing other processes from accessing it.
The compiler warning might actually be telling you that:
using (StreamReader reader = new StreamReader(fullPath))
{
// All stream-related operations go here
}
// Stream is closed here, whether the execution was correct or an exception was thrown.
oooo okay ill update my stuff
also i tried looking up your message about out Type
maybe i read through it too fast but thats supposed to work with what im doing?
Yeah, I saw your question context posted here and realized it's not what you want
okay
You can manipulate that variable from inside the method just like that. That code at least in relation to the text field is valid
The using scope can also be implicit:
using StreamReader reader = new StreamReader(fullPath);
It will be disposed at the end of the current scope.
Something else is fucking it up
its being called from another method
(given that they're using C#8 and above, below it won't compile)
also do u still do reader.close in the using?
At this point I want to look at your entire class
Nope, no need. It takes care of it automatically
cool
a powerful website for storing and sharing text and code snippets. completely free and open source.
@livid kraken ?
chill Im reading it
man youre so intense lmao
does the error happen when you call it from ConfirmLanguage or when you call it from the menu ?
you havent hit that breakpoint
i did tho
there should be a yellow arror at it and the code should stop
it went through to the method
it threw an error on line 204
past the break point
breakpoints dont go through on their own
how do they work in unity then
I wanted you to stop on that line so we can look at the inputCode variable
so it skipped it ?
yes
so that part of the code is not being called then
but it must be cause the error is being thrown where the method is
did you attach the debuger ?
^
the play button in visual studio
this is my first project in unity lol idk
just setting a breakpoint wont do much if you dont start a debuger
Is there a way to reference the Build Scene list? Either as a List or as an Enum?
no thats for a build
I told you the green play button in visual studio
click that then hit play in unity
but all this is going to lead us to is a way to output from inside a method without passing the tmp as an arugment
so like
thats the answer
im just trying to find it
Hmm, the green arrow in VS should be saying "Attach to Unity", make sure you have that
if its trying to start the project your VS is not configured probably so go to #854851968446365696 and configure it
its probably fine cause it works for everything else
i know this is just this one error
what you want is really basic there is nothing special about it something else is wrong with your code
yes it is basic
and it works
but not in this context
and i dont think its the visual studio configurations stopping it
i think theres a certain way to do it
there is no certain way you can access the variable directly in the method
or pass it as a param it does not matter
it works if u pass it tho
right now in the code you showed you are passing it and you are still getting a null reference
i am not passing it properly though
i mean of course cause im getting an error
but like im trying to find a way around this
i know the way around this i think but i want to find an easier way
my bet is still on having another instance of the component in the scene. I have to go now sorry
Catching up, hang on
Alright, so as Uri said, we'll check for duplicate script instances.
In Start, paste the following line of code
Debug.Log("Script Start received", gameObject);
The second argument denotes the "sender" of the log, when you'll select it, the object that sent it will be highlighted in your Hierarchy
Just make sure Collapse is off in the Console settings
?
So, only one log, and when you select it, the right GameObject gets highlighted in the hierarchy?
yes
Same thing in Start, but this time log testCases
just one
And the contents of the log, not empty?
Debug.Log(testCases) must not produce an empty message after the log timestamp
unsure what that means exactly but
Yeah, so it has a value. No idea on what's going on here
:(
It throws on this line, right?
testCases.text = reader.ReadToEnd();
yes
Very weird. Just before that line, can you paste that code
Debug.Log(testCases);
Debug.Log(reader);
And ensure the first log says "TMPro.TMP_InputField", and the second one "System.IO.StreamReader"?
Uhh, says "Null" now? Wtf???
So, it's getting de-referenced somewhere between Start and that point
yeah
lol but how do i reference it from inside that method
that was the question π₯²
lmao
It should be working as is, what I don't understand is how it suddenly becomes null
I may have a solution, but you'll have to make the debugger work and attach to Unity
whats your idea
Trying to break (stop app execution) when the contents of the variable changes
i dont think it changes
It's a trigger you can make when using the debugger
i just dont think its pointing to the same variable
Can you post the updated code again, so we're on the same page?
wait are you trying to reference an instance member in a static method? because you can't do that. the method has to be non-static or you have to pass it as a parameter
Ahh got it
yeah pass it as a parameter for the method or don't make the method static
Variablefriend got me on the track
if you cant do either of those
Your parameter and class field are named the same, so it prioritizes the parameter
You're actually never referring to the class field in that method
If what you wanted to do is bypass the parameter of course
i may need an explain like im 5 for that
submitCode.ConfirmLanguage();```
cause these are the same it doesnt work?
in a static method you can only operate on static members or things passed as an argument when calling the method. You cannot reference a non-static class variable inside of it. I also recall you showing SubmitCode is a MonoBehaviour which means you can't call a constructor with the new keyword
From the latest version of the code I can see, the method isn't static
ah, i haven't actually seen any code recently. They just said it was a static method
Yep, but no problem here, since you're creating a new instance of the class, and you call ConfirmLanguage on it
Wait
a powerful website for storing and sharing text and code snippets. completely free and open source.
Big problem actually
yeah can't new a MonoBehaviour
new shouldn't be used with MonoBehaviour
so what do i do lol
take out monobehaviour?
ive never gotten to this point yet
idek what monobehaviour even means tbh
apologies
if you intend for it to be a component on a gameobject it needs to be a MonoBehaviour.
You have to reference an instance of the class which means you have to pass an instance to the static method you are calling
Removing MonoBehaviour will prevent any Unity message like Start to be executed on the code
@sly grove im new with unity lol
And, if you don't need that script to be attached to a GameObject indeed, then remove MonoBehavoiur
Epic ping fail
You'll have to make the method non-static
Other scripts will need an instance of that script to call the formerly static method
get a reference to the game object that has the SubmitCode component on it. There are many ways to get a reference, here are my preferred ways: https://www.youtube.com/watch?v=Ba7ybBDhrY4
What would be a better way to update the game files without Unity Remote?
Unity remote does not update your game files.
Then how does the function of enabling and disabling feature is being called?
idk if these do what i need them to do maybe
What?
you just need a reference to an instance of SubmitCode. In any of the examples shown in the video you can change GameObject to SubmitCode for the variable type and it will work
on button click in a different script it calls the setValues
then this calls the confirmlanguage
Nvm, how should I implement an auto downloander for my game? I've already made a version check
right and you need to call SetValuesFromDB on an instance of SubmitCode. You can't create a new instance of a MonoBehaviour with the new keyword so you need to get an instance of the object using one of the many ways to reference other objects
I'm almost curious. How does your version check work? π
Post call and check with a file on github
Then show a pop-up if the versions don't match
Okay, and what platform are you supporting?
Win and unix
?
im bad
maybe im not understanding how to create an instance
I have to support both platforms as its a requirement for eos
you're now attempting to call it like a static method. An instance of the object would be a reference to a currently active SubmitCode in the scene. Which you would use one of the several ways to reference game objects in that video i linked to get a reference to
IEnumerator Voice()
{
AudioSource audio = audioSource.GetComponent<AudioSource>();
audio.clip = voiceClips[index];
audio.Play();
yield return new WaitForSeconds(audioSource.clip.length);
while(audio.isPlaying) //The problem.
{
if(!currentlyOnDialogue)
{
audio.Stop();
}
}
}
I am developing a dialogue system the problem is that when the players close the dialogue window before the end of the voice line, the voice line continues to play. So I created a simple while loop to prevent this, but this loop strangely affects the performance of my game. I need help...
You need a yield return null in there
Otherwise you're not going to finish the frame until the audio stops playing
here's what you need to do:
- get a reference to an instance of SubmitCode using one of the referencing methods I demonstrated in the video
- call your method on that instance like so:
myReferenceToSubmitCode.SetValuesFromDB();
After the audio.Stop()?
No, inside the loop
Otherwise you're going to keep looping within the same frame, never allowing the frame to finish until the audio is done
afaik, there's really no clean way to "update" a unity player without actually reinstalling. You can use asset bundles / addressables but that's additional assets rather than an update. You should check if whatever you are using to distribute it (steam?) has automatic update support
Eos stands for epic online services :D
I've seen some projects of self updating IL2CPP and I was curious how they work tbh
And... Problem solved!
Looks like I need to learn more about coroutines
Thanks for the help β€οΈ
wait is that your video?
yes
Ah, don't have a clue about how epic does it. And I also just realized you were talking about Unity remote config and not unity remote π . But I'd suggest looking into eos docs and see if they already have something like this implemented already
ima spend more time lol idk whats not getting through to me but thank you for the resources and help
@thin mesa @fresh salmon
They don't sadly, I've searched for a solution there already. That's why I've come and ask here. I've tried to make a launcher in c++ and download and replace the files with the new ones but the Easy Anticheat did not like the hashes
Is there a way to get a dedicated server for an unity game for free?
how do i make a card n fill its values? im now able to use a cardtemplate, with public variables Card(which stores its values). and the other public variables of card, atk hp are taken from references of UI elements that are children of the template. but now im trying to make a CreateCard cs script that takes a Card(card data) and CardTemplate and instantiate a card. but i cant seem to instantiate a card then fill in its values. the only way i managed to do it is to use the code to instantiate the card then drag in the Card data manually...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateCard : MonoBehaviour
{
public GameObject cardTemplate;
public Card card;
public void createCard()
{
GameObject createdCard = Instantiate(cardTemplate);
createdCard.GetComponent<CardDisplay>().setCard(card);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class CardDisplay : MonoBehaviour
{
public Card card;
public new TextMeshProUGUI name;
public TextMeshProUGUI description, attack, cost, health;
public Image cardImage;
private void Update()
{
initValues();
}
private void initValues()
{
name = card.name;
description = card.description;
attack.SetText(card.attack.ToString());
cost.SetText(card.cost.ToString());
health.SetText(card.health.ToString());
cardImage.sprite = card.cardImage;
}
public void setCard(Card c)
{
card = c;
}
}
Are you getting any errors?
